2014-01-23 158 views
0

在Xamarin中,如何將用戶定義的對象(我寫的類)傳遞給不同的活動?將對象傳遞給新活動

我想傳遞的對象是一個列表,名爲項目:

_mapLocationList[0] 

的產品類型:

MapLocation 

這裏是我當前的代碼:

intent.PutExtra ("MapLocation", _mapLocationList[0]); 

上面的方法可以用來傳遞一個對象嗎?如果沒有,我該怎麼做?

預先感謝

回答

1

傳遞對象到Activity的最簡單的方法是使用Intent秒。爲此,你需要你的班級implementSerializableParcelable

這樣,您就可以通過putExtra("myobject", object)方法將您的對象放在Intent中,然後在其他Activity中用getSerializableExtra("myobject")恢復它。

例如:

在第一Activity

final Intent intent = new Intent(this, SecondActivity.class); 
intent.putExtra("my_class", your_maplocation_object); 
startActivity(intent); 

然後在你的第二Activity,你會怎麼做:

final Intent passedIntent = getIntent(); 
final MapLocation my_class = (MapLocation) passedIntent.getSerializableExtra("my_class"); 
0

還有一種更簡單,很愉快的方式:使用Googe GSON庫。

序列化的活動答:

intent.putExtra("mapLocExtra", new Gson().toJson(myMapLocationObject,MapLocation.class); 
startActivity(intent); 

*** Deserialisation在活動B:*

@Oncreate(...){ 

String mapLocJson= getIntent().getExtra("mapLocExtra").toString(); 
MapLocation mylocationObject= new Gson().fromJson(maplocJson,MapLocation.Class); 

//do Stuff With mylocationObject 
    } 

更多的相關信息:https://code.google.com/p/google-gson/

+0

好主意,但不會與GSON工作。將其替換爲ServiceStack.Text或Json.NET序列化程序。他使用Xamarin ...;) – SKall

相關問題