Best practice for instantiating a new Android Fragment

前端 未结 13 1511
暖寄归人
暖寄归人 2020-11-21 04:38

I have seen two general practices to instantiate a new Fragment in an application:

Fragment newFragment = new MyFragment();

and

<         


        
13条回答
  •  心在旅途
    2020-11-21 05:18

    I disagree with yydi answer saying:

    If Android decides to recreate your Fragment later, it's going to call the no-argument constructor of your fragment. So overloading the constructor is not a solution.

    I think it is a solution and a good one, this is exactly the reason it been developed by Java core language.

    Its true that Android system can destroy and recreate your Fragment. So you can do this:

    public MyFragment() {
    //  An empty constructor for Android System to use, otherwise exception may occur.
    }
    
    public MyFragment(int someInt) {
        Bundle args = new Bundle();
        args.putInt("someInt", someInt);
        setArguments(args);
    }
    

    It will allow you to pull someInt from getArguments() latter on, even if the Fragment been recreated by the system. This is more elegant solution than static constructor.

    For my opinion static constructors are useless and should not be used. Also they will limit you if in the future you would like to extend this Fragment and add more functionality to the constructor. With static constructor you can't do this.

    Update:

    Android added inspection that flag all non-default constructors with an error.
    I recommend to disable it, for the reasons mentioned above.

提交回复
热议问题