Do fragments really need an empty constructor?

后端 未结 4 1508
星月不相逢
星月不相逢 2020-11-22 07:12

I have a Fragment with a constructor that takes multiple arguments. My app worked fine during development, but in production my users sometimes see this crash:<

4条回答
  •  花落未央
    2020-11-22 07:45

    Here is my simple solution:

    1 - Define your fragment

    public class MyFragment extends Fragment {
    
        private String parameter;
    
        public MyFragment() {
        }
    
        public void setParameter(String parameter) {
            this.parameter = parameter;
        } 
    }
    

    2 - Create your new fragment and populate the parameter

        myfragment = new MyFragment();
        myfragment.setParameter("here the value of my parameter");
    

    3 - Enjoy it!

    Obviously you can change the type and the number of parameters. Quick and easy.

提交回复
热议问题