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
The Fragment class also should not be an inner class, because it is instantiated out of your Activity class scope. Nested class is ok.
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.
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.
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.
Adding
static
Fixed it for me
public class MyFragment extends Fragment