[英]Android: How to pass Parcelable object to intent and use getParcelable method of bundle?
Why bundle has getParcelableArrayList
, getParcelable
methods;为什么 bundle 有getParcelableArrayList
、 getParcelable
方法; but Intent
has only putParcelableArrayListExtra
method?但是Intent
只有putParcelableArrayListExtra
方法? Can I transmit only object<T>
, not ArrayList
of one element?我可以只传输object<T>
而不是一个元素的ArrayList
吗? Then, what is getParcelable
for?那么, getParcelable
有什么用呢?
Intent provides bunch of overloading putExtra() methods. Intent 提供了一堆重载putExtra()方法。
Suppose you have a class Foo implements Parcelable properly, to put it into Intent in an Activity:假设您有一个类 Foo 正确实现了 Parcelable,将其放入 Activity 中的 Intent 中:
Intent intent = new Intent(getBaseContext(), NextActivity.class);
Foo foo = new Foo();
intent.putExtra("foo ", foo);
startActivity(intent);
To get it from intent in another activity:从另一个活动的意图中获取它:
Foo foo = getIntent().getExtras().getParcelable("foo");
Hope this helps.希望这可以帮助。
Parcelable p[] =getIntent().getParcelableArrayExtra("parcel");
Sender Activity:发件人活动:
val intent = Intent(this, RestaurantDetails::class.java)
intent.putExtra(Constants.RESTAURANT, restaurant)
startActivity(intent)
Receiver Activity:接收器活动:
val restaurant = intent.getParcelableExtra<Restaurant>(Constants.RESTAURANT)
It is important to remember that your models must implement the Parcelable interface, and the static CREATOR method.请务必记住,您的模型必须实现Parcelable接口和静态CREATOR方法。 This case is for the lists此案例适用于列表
private static final String MODEL_LIST = "MODEL_LIST";
public MainFragment() {}
public static MainFragment newInstance(ArrayList<YourModel>
models) {
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
args.putParcelableArrayList(MODEL_LIST,models);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
ArrayList<YourModel> models = getArguments().getParcelableArrayList(MODEL_LIST);
}
}
First create Parcelable using Given Technique then首先使用Given Technique创建 Parcelable 然后
public static CreditCardDetail newInstance(CreditCardItemBO creditCardItem) {
CreditCardDetail fragment = new CreditCardDetail();
Bundle args = new Bundle();
args.putParcelable(CREDIT_KEY,creditCardItem);
fragment.setArguments(args);
return fragment;
}
And getting it like并得到它喜欢
if(getArguments() != null)
{
creditCardItem = getArguments().getParcelable(CREDIT_KEY);
}
where在哪里
public static final String CREDIT_KEY = "creditKey";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.