【问题标题】:Android. Remove inflated Fragment when screen orientation changes(Portrait <-> Landscape)?安卓。屏幕方向改变时删除膨胀的片段(纵向<->横向)?
【发布时间】:2017-02-12 15:38:03
【问题描述】:

MainActivity 像这样膨胀一个片段:

getSupportFragmentManager().beginTransaction()
            .replace(R.id.dashboard_fragment_container, df, TAG_DASHBOARD_FRAGMENT)
            .commit();

但是当屏幕方向改变时,我希望删除(销毁)这个片段。

有什么简单的方法可以检测到屏幕何时将发生变化,以便我可以移除膨胀的片段?

【问题讨论】:

标签: android android-fragments


【解决方案1】:

尝试使用 onConfigurationChanged() 方法。它会检测屏幕方向的变化。

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
        //remove fragment
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

在onCreate()中设置这些条件,因为方向改变会再次调用onCreate()方法:

if(Activity.getResources().getConfiguration().orientation == ORIENTATION_PORTRAIT){
  getSupportFragmentManager().beginTransaction()
            .replace(R.id.dashboard_fragment_container, df, TAG_DASHBOARD_FRAGMENT)
            .commit();
}

让我知道这是否有效。

【讨论】:

    【解决方案2】:

    Fragments 通常会在 configuration 更改时重新创建。如果您不希望发生这种情况,请使用

    片段构造函数中的setRetainInstance(true);

    这将导致在配置更改期间保留片段。

    Docs

    现在当 Activity 因为方向改变而重新启动时,Android 框架会自动重新创建并添加 Fragment。

    如果您想在configuration 更改使用期间删除片段:

    活动中

     @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    
        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
        }
    }
    

    也在清单中:

    <activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">
    

    现在在 Activity 的 onCreate() 中删除 Fragment 使用:

        Fragment f = getSupportFragmentManager().findFragmentById(R.id.content_frame);  //your fragment
    if(f == null){
        //there is no Fragment
    }else{
        //It's already there remove it
        getSupportFragmentManager().beginTransaction().remove(f).commit();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多