Pass object data between fragments and activity in android

前端 未结 2 1293
悲哀的现实
悲哀的现实 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: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();
    

提交回复
热议问题