Member variables vs setArguments in Fragments

前端 未结 4 815
攒了一身酷
攒了一身酷 2020-12-12 13:02

I\'ve noticed that in the Android reference for Fragments (notably DialogFragment) that they do a couple of things different from what I\'d expect:

1). Use pub

4条回答
  •  时光取名叫无心
    2020-12-12 13:44

    I found this to be a HIGHLY confusing issue (one of many that litter the Android landscape).

    setArguments() is a workaround for Android's very unhelpful need to have a parameter-less constructor available for Fragments.

    My confusion came in waves. First, the methods you naturally override in your Fragment (e.g. onCreate, onCreateView) receive a Bundle parameter that represents the savedInstanceState of your Fragment. This instance state apparently has NOTHING whatsoever to do with the values you store via setArguments() and retrieve via getArguments(). Both use a Bundle, both Bundles are likely to be accessed within the same overridden method, neither have anything to do with each other.

    Second, it's unclear how Android uses setArguments(). Android calls your parameter-less constructor to rebuild your Fragment on rotate, but apparently ALSO will call whichever setArguments() method was last called when the Fragment was constructed.

    Huh????

    Amazing, but true. All of this creating Bundles with setArguments() madness exists to compensate for the need of a parameter-less Fragment constructor.

    In short, I'm using the static newInstance method to create my Fragment.

    public MyFragment() {
        //satisfy Android
    }
    
    public static MyFragment newInstance(long record_id) {
        Log.d("MyFragment", "Putting " + record_id + " into newInstance");
        MyFragment f = new MyFragment();
        Bundle args = new Bundle();
        args.putLong("record_id", record_id);
        f.setArguments(args);
        return f;
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /**
         * Perform an immediate check of arguments,
         * which ARE NOT the same as the bundle used
         * for saved instance state.
         */
        Bundle args = getArguments();
        if(args != null) {
            record_id = args.getLong("record_id");
            Log.d("MyFragment", "found record_id of " + String.valueOf(record_id));
        }
        if(savedInstanceState != null) {
            //now do something with savedInstanceState
        }
    }
    

提交回复
热议问题