Fragment activity crashes on screen rotate

前端 未结 5 588
刺人心
刺人心 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:39

    The Fragment class also should not be an inner class, because it is instantiated out of your Activity class scope. Nested class is ok.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-01 18:56

    I faced the similar problem when I renamed my project package name. The fragment class is referred by xml layout and usually contains the full package name.Thats where the problem was. My fragment class name was still having old package name.

    0 讨论(0)
  • 2021-01-01 18:57

    Well, as you error says, something is wrong with your MyFragment class. Make sure you have something like:

    public class MyFragment extends Fragment
    

    when declaring your fragment class. Also, you shouldn't have any constructor in the class. So make sure that you don't have one.

    If you post the code for your Fragment class we might be able to help you better.

    0 讨论(0)
  • 2021-01-01 18:57

    Adding

    static
    

    Fixed it for me

    public class MyFragment extends Fragment
    
    0 讨论(0)
提交回复
热议问题