下面是我的代碼:savedInstanceState總是在片段空
public class MyListFragmentActivity extends FragmentActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("DEBUG : MLFA onCreate");
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(fragmentID, new MyListFragment())
.replace(detailFragmentID, new MyDetailFragment()).commit();
}
}
@Override
protected void onRestart() {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
Fragment prevFrag = getSupportFragmentManager().findFragmentById(detailFragmentID);
if (prevFrag != null) {
fragmentTransaction.remove(prevFrag);
getSupportFragmentManager().beginTransaction().replace(detailFragmentID, new MyDetailFragment()).commitAllowingStateLoss();
} else {
getSupportFragmentManager().beginTransaction().replace(detailFragmentID, new MyDetailFragment()).commitAllowingStateLoss();
}
}
MyListFragment
public class MyListFragment extends Fragment{
//When we click on each item in list view call detail fragment to relad its layout
OnItemClickListener onItemClickListener = new OnItemClickListener() {
/** Getting the fragmenttransaction object, which can be used to add, remove or replace a fragment */
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
/** Getting the existing detailed fragment object, if it already exists.
* The fragment object is retrieved by its tag name
* */
Fragment prevFrag = getFragmentManager().findFragmentById(detailFragmentID);
/** Remove the existing detailed fragment object if it exists */
if (prevFrag != null) {
fragmentTransaction.remove(prevFrag);
MyDetailFragment mydetailFragment = new MyDetailFragment();
fragmentTransaction.replace(detailFragmentID, mydetailFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.show(getFragmentManager().findFragmentById(detailFragmentID));
fragmentTransaction.commit();
}
}
MyDetailFragment
public class MyDetailFragment extends Fragment{
@Override
public void onCreate(Bundle savedInstanceState) {
setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (savedInstanceState != null) {
// it is not entering the inside here
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// saving some values
}
當我的標題我的設備後,我設置setRetainInstance(true);
savedInstanceState始終爲空,那麼我如何才能在此保存我的值?
爲什麼這麼說?我在這裏做錯了什麼,以及如何解決這個問題?