Fragment activity crashes on screen rotate

前端 未结 5 626
刺人心
刺人心 2021-01-01 18:22

I have a simple fragment activity. In the onCreate() method, I simply add a fragment. The code is posted below. However, each time I rotate the screen, system will call onCr

5条回答
  •  青春惊慌失措
    2021-01-01 18:54

    Your Fragment shouldn't have constructors because of how the FragmentManager instantiate it. You should have a newInstance() static method defined and pass any parameters via arguments (bundle)

    For example:

    public static final MyFragment newInstance(int title, String message)
    {
        MyFragment fragment = new MyFragment();
        Bundle bundle = new Bundle(2);
        bundle.putInt(EXTRA_TITLE, title);
        bundle.putString(EXTRA_MESSAGE, message);
        fragment.setArguments(bundle);
        return fragment ;
    }
    

    And read these arguments at onCreate:

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        title = getArguments().getInt(EXTRA_TITLE);
        message = getArguments().getString(EXTRA_MESSAGE);
    
        //...
    
    }
    

    This way if detached and re-attached the object state can be stored through the arguments, much like bundles attached to Intents.

提交回复
热议问题