更改方向在DrawerLayout中更改我的片段

时间:2015-10-02 07:10:15

标签: android android-fragments screen-orientation drawerlayout

我的fragments中有三个DrawerLayolut

  • 片段A

  • 片段B

  • 片段C

    默认情况下(在应用的初始化版本中)我加载了FragmentA:如果我去了,例如,FragmentB效果很好。

问题:当我在FragmentB中旋转屏幕时,我回到了FragmentA

我不知道如何避免这种情况。我尝试使用onCreate的{​​{1}}中的下一个代码:

AppCompatActivity

但是没有像我预期的那样工作......请问,有人帮我解决了我的问题吗?欢迎任何帮助

我读到了另一个解决方案:

Fragment mFragment = null;

if(getSupportFragmentManager().findFragmentById(R.id.myframe) == null) {

   mFragment = new CalendarioFragment();
   getSupportFragmentManager().beginTransaction().add(R.id.myframe, mFragment ).commit();

} else {

   if(mFragment instanceof FragmentA){
       mFragment = (FragmentA) getSupportFragmentManager().findFragmentById(R.id.myframe);

   }else if(mFragment instanceof FragmentB){
       mFragment = (FragmentB) getSupportFragmentManager().findFragmentById(R.id.myframe);

   }else if(mFragment instanceof FragmentC){
       mFragment = (FragmentC) getSupportFragmentManager().findFragmentById(R.id.myframe);

   }
}

但我认为这不值得推荐......(并且不适合我)

1 个答案:

答案 0 :(得分:1)

<activity android:name="CalActivity" android:configChanges="orientation|keyboardHidden"/>一起,您需要在onConfigurationChanged()中致电Activity。看起来应该是这样的:

@Override
public void onConfigurationChanged(Configuration config) {
    super.onConfigurationChanged(config);
    // Your code here to replace fragments correctly
}

这是关于此主题的Android API指南:Handling Runtime Changes

尽管如你所说,不推荐这样做,但更好的解决方案是使用onSavedInstanceStateonRestoreInstanceState,如下所示:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putInt("currentFragment", 2);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    int fragmentNum = savedInstanceState.getInt("currentFragment");
    // Restore fragment based on fragmentNum
}

有关详情,请参阅此问题:Saving Activity State on Android

相关问题