屏幕方向更换后如何恢复碎片

时间:2015-09-07 01:50:08

标签: android android-fragments screen-orientation

我有两个片段的活动:DogFragment,LegoFragment。在肖像模式中,我展示了DogFragment,在横向模式中,我展示了LegoFragment。我的问题是碎片在旋转后不记得它们的状态。有没有办法保存片段的状态?了解在方向更改期间重新创建活动,并根据我创建的方向并将DogFragment或LegoFragment附加到活动。

以下是我添加片段的活动的onCreate方法。

@Override

protected void onCreate(Bundle savedInstanceState) {
   
  super.onCreate(savedInstanceState);
    
  setContentView(R.layout.activity_main);

  if (getResources().getConfiguration().orientation == 
     Configuration.ORIENTATION_PORTRAIT) {

   addDogFragment();

  } else {
  
    addLegoFragment();

  }

}

private void addDogFragment() {
  DogFragment fragment = DogFragment.newInstance(null, null);
   
  getSupportFragmentManager().beginTransaction().
  replace(R.id.fragment_container, fragment).commit();

}



private void addLegoFragment() {

  LegoFragment fragment = LegoFragment.newInstance(null, null);
    
  getSupportFragmentManager().beginTransaction().
  replace(R.id.fragment_container, fragment).commit();

}

我知道FragmentManager有我的片段的副本。但我不确定解决这个问题的最佳方法。如果我使用标记调用replace,我是否只需找到ByTag然后再次调用replace?或者有一种标准的方法来做这些事情吗?

2 个答案:

答案 0 :(得分:1)

试试这个,为LegoFragment创建一个类似的功能

private void setDogFragment() {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    Fragment removeFragment = mFragmentManager.findFragmentByTag("lego");
    if (removeFragment!=null) {
        transaction.detach(removeFragment);
    }
    Fragment fragment = mFragmentManager.findFragmentByTag("dog");
    if (fragment != null) {
        transaction.attach(fragment);
    } else {
        fragment = new DogFragment();
        transaction.add(R.id.fragment_container, fragment,
                "dog");
    }
    transaction.commit();
}

答案 1 :(得分:0)

if (getResources().getConfiguration().orientation == 
 Configuration.ORIENTATION_PORTRAIT)
    attachFragment(R.id.fragment_container, "dogFragment",     DogFragment.class.getName());
else 
    attachFragment(R.id.fragment_container, "legoFragment", LegoFragment.class.getName());


private FragmentTransaction mCurTransaction;
private FragmentManager mFragmentManager;
public void attachFragment(int containerViewId, String tag, String fragmentClassName){
    if (mFragmentManager == null)
        mFragmentManager = getSupportFragmentManager(); // or getFragmentManager();

    if (mCurTransaction == null)
        mCurTransaction = mFragmentManager.beginTransaction();

    // Do we already have this fragment?
    Fragment fragment = mFragmentManager.findFragmentByTag(tag);
    if (fragment != null){
        mCurTransaction.attach(fragment);
    }else {
        fragment = Fragment.instantiate(this, fragmentClassName);
        mCurTransaction.add(containerViewId, fragment, tag);
    }
}