I have a fragment in an activity containing two layouts to show each for different orientations.
For portrait orientation, firstLayout.
For landscape orientation, secondLayout.
Both the layouts are shown in a same container.
So I have something like -
if ((getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
&& getActivity().findViewById(R.id.fragment_container) != null)
{
view = inflater.inflate(R.layout.firstLayout, container, false);
//data
return view;
}
else
{
view = inflater.inflate(R.layout.secondLayout, container, false);
return view;
}
So when the user rotates the device (portrait to landscape), layout secondLayout
is called.
When the user again rotates the device while in a layout secondLayout
, the other layout of the fragment i.e. layout firstLayout
is called back in.
The problem is -
The layout firstLayout
is taking so much time to load back as if application hanged for some time as it is doing so much of initialization stuff in onCreate()
.
Having so, I wanted that layout firstLayout
should be called without a call to onCreate()
in a fragment.
So I just did-
android:configChanges="orientation|screenSize"
and then overridden the method onConfigurationChanged(Configuration newConfig)
by just inflating my layout firstLayout
. But by doing this I lost my previous data.
I also heard about setRetainState(true)
to use to retain the previous state but I am not sure how to use it to get the previous data on orientation change.
What is the best way to show the layout firstLayout
on orientation change in as faster way as it is when it appears when user clicks the back button (for example)?