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

How to recover fragments after screen orientation replacement

我有一个 activity,其中包含两个片段:DogFragment、LegoFragment。在纵向模式下,我显示 DogFragment,在横向模式下,我显示 LegoFragment。我的问题是片段在旋转后不记得它们的状态。有没有办法保存片段的状态?了解 activity 是在方向更改期间重新创建的,并且基于我创建的方向并将 DogFragment 或 LegoFragment 附加到 activity。

这是 activity 的 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 ,我是否只是 findByTag 然后再次调用 replace ?或者有没有标准的方法来做这些事情?

试试这个,为 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();
}
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);
    }
}