I currently have a fragment attached to the activity. When I rotate my device, expect the details and position of grid to be saved and restored when the view is created again. The onSavedStateInstance()
runs fine and I bundle up everything, but when the onCreateView()
of the fragment is invoked, the stateInstance is null
. I know a similar question has been asked and answered before but it did not really help in my case. Here are some snippets that may be useful to debug.
MainActivityFragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
if (savedInstanceState != null) {
gridViewObjects = (List<GridViewObject>) savedInstanceState.get(movieKey);
position = savedInstanceState.getInt("position");
} else {
gridViewObjects = new ArrayList<>();
}
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelableArrayList(movieKey, (ArrayList) gridViewObjects);
outState.putInt("position", gridView.getFirstVisiblePosition());
super.onSaveInstanceState(outState);
}
fragment_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="app.sunshine.android.example.com.popmovies.MainActivityFragment">
<GridView
android:id="@+id/fragment_main_gridView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:gravity="center"
android:numColumns="2"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp" />
</FrameLayout>
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.indigo_500)));
setContentView(R.layout.activity_main);
}
Edit: On debug, I see that on device orientation change, the activity is re-created and the savedInstanceState in OnCreate()
method is not null. The bundle details are intact. It's only when the fragment is created, the savedInstanceState in OnCreateView()
is null.
Any help appreciated!