I'm new to android and I'm facing the following problem. I'm developing for both, Android 2 and 3, and this is why I use fragments. However to make the app working on Android 2 devices I import android.support.v4.app.ListFragment. I need to maintain selection within my ListFragment when orientation of the screen changes. I'm overriding onSaveInstanceState()
method and put an int into the bundle. When the screen is rotated, this method is called and the int is added to the bundle. However when onActivityCreated()
is called, its bundle is null. I am following the example provided on Android website: http://developer.android.com/reference/android/app/Fragment.html, but as mentioned above - after onSaveInstanceState()
is called, the bundle in onActivityCreated()
is still null.
Here's the code:
import android.support.v4.app.ListFragment;
public class VisitsHomeFragment extends ListFragment {
private int selectedPosition = -1;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("SELECTED_POSITION")) {
selectedPosition = savedInstanceState.getInt("SELECTED_POSITION");
}
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("SELECTED_POSITION", selectedPosition);
}
}
I would appreciate any help with this problem.
I had the same problem, adding android:id
to the fragment element in the layout file fixed this issue.
It seems FragmentManager
uses the id to send the appropriate bundle when recreating a fragment.
Make sure you're not calling setRetainInstance(true)
in the Fragment
. After a little experimentation I pinpointed this as being the error in my code. The downside of having to do it this way is one has to manually bundle all instance data.
After removing the method call and updating my onSaveInstanceState
to parcel all of my instance variables, I can now restore list position on rotation.
I had the same problem, and I eventually tracked it down to having different android:id attribute values on the fragment elements in the two different layouts (portrait and landscape).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With