使用 Parcelable 将对象从一个 android 活动传递到另一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10975239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use Parcelable to pass an object from one android activity to another
提问by Namratha
I want to do this
我想做这个
class A extends Activity{
private class myClass{
}
myClass obj = new myClass();
intent i = new Intent();
Bundle b = new Bundle();
b.putParcelable(Constants.Settings, obj); //I get the error The method putParcelable(String, Parcelable) in the type Bundle is not applicable for the arguments (int, A.myClass)
i.setClass(getApplicationContext(),B.class);
startActivity(i);
}
How do I use Parcelable to pass obj to activity B?
如何使用 Parcelable 将 obj 传递给活动 B?
采纳答案by Jon Skeet
As the error suggests, you need to make your class (myClass
in this case) implement Parcelable
. If you look at the documentation for Bundle
, all the putParcelable
methods take either a Parcelable
or a collection of them in some form. (This makes sense, given the name.) So if you want to use that method, you need to have a Parcelable
instance to put in the bundle...
正如错误所暗示的那样,您需要让您的类(myClass
在本例中)实现Parcelable
. 如果您查看 的文档Bundle
,则所有putParcelable
方法Parcelable
都以某种形式采用它们的一个或集合。(鉴于名称,这是有道理的。)因此,如果您想使用该方法,则需要将一个Parcelable
实例放入包中...
Of course you don't haveto use putParcelable
- you could implement Serializable
instead and call putSerializable
.
当然,你不具备使用putParcelable
-你可以实现Serializable
,而不是和呼叫putSerializable
。
回答by Paresh Mayani
Create your class and implements Serializable:
创建您的类并实现Serializable:
private class myClass implements Serializable {
}
And do like:
并且喜欢:
myClass obj = new myClass();
Intent aActivity = (A.this, B.class);
intent.putExtra("object", obj);
On Receiving side:
在接收端:
myClass myClassObject = getIntent().getSerializableExtra("object");
回答by Jimit Patel
Parcelable is pain in writing code but more cost effective than Serializable. Have a look at the given below link -
Parcelable 在编写代码时很痛苦,但比 Serializable 更具成本效益。看看下面给出的链接 -