问题
The Fragments in my app are not re-added to the activity's view when the device is rotated. If i understand the documentation (and similar questions here on SO) correctly, this should be handled be the fragment manager (without having to specify android:configChanges in my manifest).
My Activity looks like:
public class MainActivity extends SherlockFragmentActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.add(R.id.main_fragment_placeholder, new DashboardFragment(),"dashboard")
.commit();
}
}
}
And a Fragment looks like (omitted clicklisteners and so on for clarity):
public class DashboardFragment extends SherlockFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
}
}
The layout files look like (activity_main.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/main.main">
<FrameLayout android:id="@+id/main_fragment_placeholder"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_width="0px"
/>
</LinearLayout>
And fragment_layout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main.wrapper"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<my.layout.DashboardLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/main.dashboard">
<!-- some buttons here -->
</my.layout.DashboardLayout>
</LinearLayout>
However, when i rotate my device the screen always becomes blank.
回答1:
Turns out I did a Stupid Thing. I overrode the onSaveInstanceState(...)
method in my activity, without calling super.onSaveInstanceState()
, which resulted in the fragments not being recreated. Posting the answer here in hopes that I can save somebody else the time!
回答2:
Fragments usually get recreated on configuration change. If you don't wish this to happen, use
setRetainInstance(true);
in the Fragment's constructor(s)
This will cause fragments to be retained during configuration change.
http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)
来源:https://stackoverflow.com/questions/13065043/fragment-not-re-added-after-orientation-change