Android: How to pass Parcelable object to intent a

2019-01-04 02:46发布

Why bundle has getParcelableArrayList, getParcelable methods; but Intent has only putParcelableArrayListExtra method? Can I transmit only object<T>, not ArrayList of one element? Then, what is getParcelable for?

4条回答
你好瞎i
2楼-- · 2019-01-04 02:58
Parcelable p[] =getIntent().getParcelableArrayExtra("parcel");
查看更多
ら.Afraid
3楼-- · 2019-01-04 03:08

It is important to remember that your models must implement the Parcelable interface, and the static CREATOR method. 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);
        }
    }
查看更多
淡お忘
4楼-- · 2019-01-04 03:09

First create Parcelable using Given Technique then

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";
查看更多
Evening l夕情丶
5楼-- · 2019-01-04 03:13

Intent provides bunch of overloading putExtra() methods.

Suppose you have a class Foo implements Parcelable properly, to put it into Intent in an Activity:

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.

查看更多
登录 后发表回答