Android:如何将Parcelable对象传递给Intent并使用bundle

为什么捆绑有getParcelableArrayListgetParcelable方法;但是 Intent只有putParcelableArrayListExtra方法吗?我只能传送object<T>,不能传送ArrayList一个元素吗?那是getParcelable为了什么



慕侠2389804
浏览 726回答 3
3回答

隔江千里

Intent提供了一堆重载的putExtra()方法。假设您有一个Foo类正确地实现了Parcelable,将其放入Activity中的Intent中:Intent intent = new Intent(getBaseContext(), NextActivity.class);Foo foo = new Foo();intent.putExtra("foo ", foo);startActivity(intent);要从其他活动中获取它:Foo foo = getIntent().getExtras().getParcelable("foo");希望这可以帮助。

富国沪深

重要的是要记住,您的模型必须实现Parcelable接口和静态CREATOR方法。这种情况是列表&nbsp;private static final String MODEL_LIST = "MODEL_LIST";&nbsp; &nbsp; public MainFragment() {}&nbsp; &nbsp; public static MainFragment newInstance(ArrayList<YourModel>&nbsp; &nbsp;models) {&nbsp; &nbsp; &nbsp; &nbsp; MainFragment fragment = new MainFragment();&nbsp; &nbsp; &nbsp; &nbsp; Bundle args = new Bundle();&nbsp; &nbsp; &nbsp; &nbsp; args.putParcelableArrayList(MODEL_LIST,models);&nbsp; &nbsp; &nbsp; &nbsp; fragment.setArguments(args);&nbsp; &nbsp; &nbsp; &nbsp; return fragment;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public void onCreate(Bundle savedInstanceState) {&nbsp; &nbsp; &nbsp; &nbsp; super.onCreate(savedInstanceState);&nbsp; &nbsp; &nbsp; &nbsp; if (getArguments() != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ArrayList<YourModel> models = getArguments().getParcelableArrayList(MODEL_LIST);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }

小怪兽爱吃肉

首先使用给定技术创建Parcelable,然后public static CreditCardDetail newInstance(CreditCardItemBO creditCardItem) {&nbsp; &nbsp; &nbsp; &nbsp; CreditCardDetail fragment = new CreditCardDetail();&nbsp; &nbsp; &nbsp; &nbsp; Bundle args = new Bundle();&nbsp; &nbsp; &nbsp; &nbsp; args.putParcelable(CREDIT_KEY,creditCardItem);&nbsp; &nbsp; &nbsp; &nbsp; fragment.setArguments(args);&nbsp; &nbsp; &nbsp; &nbsp; return fragment;&nbsp; &nbsp; }并得到像&nbsp;if(getArguments() != null)&nbsp;{&nbsp; &nbsp; creditCardItem = getArguments().getParcelable(CREDIT_KEY);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;}哪里public static final String CREDIT_KEY = "creditKey";
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android