Passing an Object to Fragment or DialogFragment upon Instantiation

前端 未结 4 2178
春和景丽
春和景丽 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:29

    In your DialogFragmnet class, you create two methods:

    1. newInstance to make instance of your DialogFragment

    2. setter to initialize your object

    and add setRetainInstance(true); in onCreate

    public class YourDialogFragment extends DialogFragment {
    
        ComplexVariable complexVar;
    
        public static YourDialogFragment newInstance(int arg, ComplexVariable complexVar) {
            YourDialogFragment frag = new MoveSongDialogFragment();
            Bundle args = new Bundle();
            args.putInt("count", arg);
            frag.setArguments(args);
            frag.setComplexVariable(complexVar);
            return frag;
        }
    
        public void setComplexVariable(ComplexVariable complexVar) {
            this.complexVar = complexVar;
        }
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setRetainInstance(true);
        }
    }
    

    then, to show the dialog

    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction ft = manager.beginTransaction();
    
    Fragment prev = manager.findFragmentByTag("yourTag");
    if (prev != null) {
        ft.remove(prev);
    }
    
    // Create and show the dialog.
    DialogFragment newFragment = YourFragmentDialog.newInstance(argument, yourComplexObject);
    newFragment.show(ft, "yourTag");
    

提交回复
热议问题