Pass object data between fragments and activity in android

前端 未结 2 1270
悲哀的现实
悲哀的现实 2021-01-29 01:49

I want to pass a complex object between activity and fragments as well as fragments and fragments. Currently, the main activity create a fragment input object and set that as a

相关标签:
2条回答
  • 2021-01-29 02:23

    If your fragments attach to same activity, you can store your objects in activity and access to objects like below:

    ((YourActivity)getActivity()).getYourObjects();
    

    If you are storing your objects in bundle in you activity i recommand to call the code sample i gave above in onActivityCreated() method of your fragments to avoid null pointer exception.

    If you want to pass your objects between activities or fragments in bundle. You should implement Parcelable to your objects and pass them.

    What's Parcelable? http://developer.android.com/reference/android/os/Parcelable.html

    Parcelable is more efficient but you can check Serializable: http://developer.android.com/reference/java/io/Serializable.html

    It's not a good design to pass large objects in bundle.

    Also you can pass your objects with interfaces or you can pass them with bus events. You can check Guava or OttoBus. http://square.github.io/otto/

    0 讨论(0)
  • 2021-01-29 02:32

    In this case you can use static holder (it's a bit similar to a singleton pattern).

    Create a new class

    public class Holder
    {
        private static FragmentInput input = null;
    
        public static void setInput(FragmentInput value) { this.input = value; }
        public static FragmentInput getInput() { return input; }
    }
    

    In your main activity, after you create your new FragmentInput object hold it on the Holder

    Holder.setInput(input);
    

    And you can access it anywhere, simply call

    FragmentInput myInput = Holder.getInput();
    
    0 讨论(0)
提交回复
热议问题