2014-01-23 157 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

相关问题