Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

android - Passing objects in to Fragments

I've been working with lots of Fragments recently and have been using two distinct methods of passing in objects to the Fragments, but the only difference that I can see is that in the approach taken by FragmentOne below, the object you pass in must implement the Serializable interface (and everything associated with that).

Are there any benefits to using one over the other?

public class FragmentOne extends Fragment {
    public static final String FRAGMENT_BUNDLE_KEY = 
        "com.example.FragmentOne.FRAGMENT_BUNDLE_KEY";

    public static FragmentOne newInstance(SomeObject someObject) {
        FragmentOne f = new FragmentOne();
        Bundle args = new Bundle();
        args.putSerializable(FRAGMENT_BUNDLE_KEY, someObject);
        f.setArguments(args);
        return f;
    }

    public SomeObject getSomeObject() {
        return (SomeObject) getArguments().getSerializable(FRAGMENT_BUNDLE_KEY);
    }
}

and

public class FragmentTwo extends Fragment {
    SomeObject mSomeObject;  

    public static FragmentTwo newInstance(SomeObject someObject) {
        FragmentTwo fragment = new FragmentTwo();
        fragment.setSomeObject(someObject);
        return fragment;
    }

    public void setSomeObject(SomeObject someObject) {
        mSomeObject = someObject;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are 3 ways to pass objects to a fragment

They are:

  1. Passing the object through a setter is the fastest way, but state will not be restored automatically.
  2. setArguments with Serializable objects is the slowest way (but okay for small objects, I think) and you have automatic state restoration.
  3. Passing as Parcelable is a fast way (prefer it over 2nd one if you have collection of elements to pass), and you have automatic state restoration.

http://developer.android.com/reference/android/os/Parcelable.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...