使用Parcelable从一个android的活动传递对象到另一个对象、Parcelable、android

2023-09-12 05:14:01 作者:是梦不是命

我想这样做

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);  
}

我如何使用Parcelable传递obj要b活动?

How do I use Parcelable to pass obj to activity B?

推荐答案

由于错误提示,你需要让你的(在这种情况下, MyClass的)类实现 Parcelable 。如果你看一下文档捆绑 ,所有的 putParcelable 方法将是 Parcelable 或它们的某种形式的集合。 (这是有道理的,因为这个名字。)所以,如果你想用这种方法,你需要有一个 Parcelable 实例放在包...

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...

当然,你不这样做的有无的使用 putParcelable - 你可以实现序列化而不是和呼叫 putSerializable

Of course you don't have to use putParcelable - you could implement Serializable instead and call putSerializable.