Passing an Object to Fragment or DialogFragment upon Instantiation

前端 未结 4 2179
春和景丽
春和景丽 2021-02-07 15:47

I\'m trying to work out the correct way to pass in an Object to a Fragment or DialogFragment without breaking the \'empty constructor\' rule.

For example I have created

4条回答
  •  逝去的感伤
    2021-02-07 16:27

    You can pass Object in the Bundle extras as Parcelable Objects (http://developer.android.com/reference/android/os/Parcelable.html ) and pass them to Bundle in the onCreateView(Bundle savedInstanceState). You can although save them if the user flips the screen.

    EDIT: this Parcelable tutorial was quite good!

    Another way is getting the data object from your ParentActivity, but I'm not sure if this is a good way (but it works..)

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mYourObject = ((MainActivity) getActivity()).getYourObject();
    }
    

    you have to create a Getter in your Activity for that

    public YourObject getYourObject(){
       return mYourObecjt;
    }
    

    But I guess Parcelables are the better way, because you can reuse your Fragments without any dependencies...

提交回复
热议问题