【问题标题】:How to use different fragments depending on the actual orientation? [duplicate]如何根据实际方向使用不同的片段? [复制]
【发布时间】:2019-10-21 14:00:26
【问题描述】:

我在网站上到处搜索,但没有找到答案。到目前为止,当方向改变时,我设法保持我的应用程序的重要状态,但现在我想为每个方向设置单独的片段:

If (Portrait Mode) => 将片段肖像附加到活动

if (Landscape Mode) => 将片段景观附加到活动

我不想要两个单独的布局,而是两个不同的片段(这是因为我想添加一些在纵向模式下“不可能”实现的功能)。我怎样才能做到这一点?

【问题讨论】:

    标签: java android android-fragments


    【解决方案1】:

    我们建议您在活动的 onResume() 方法中检查您的方向,如下所示。

    @Override
        protected void onResume() {
            super.onResume();
            int mOrientation = this.getResources().getConfiguration().orientation;
            if (mOrientation == Configuration.ORIENTATION_PORTRAIT) {
                // code for portrait mode
                //Add your Portarait fragment
            } else {
                // code for landscape mode
                // Add your landscape fragment
            }
        }
    

    【讨论】:

      【解决方案2】:

      您可以检查您正在附加片段的活动的onConfigurationChanged 中的方向变化。

      所以,你需要做的是,

      @Override
      public void onConfigurationChanged(Configuration newConfig) {
          super.onConfigurationChanged(newConfig);
          if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
              //set the fragment for landscape mode
          } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
               //Set the fragment for portrait mode
          }
      }
      

      另外,别忘了添加

      android:configChanges="orientation|screenSize" 在您正在处理配置更改的清单文件的活动标记中。

      【讨论】:

      • 有效!但是现在我失去了我的“状态”(实际上只是一个数组)是否有一种简单的方法来保持我的状态?据我了解,当我改变方向时,会调用 onConfigurationChanged 并且我正在膨胀适当的片段但是..这里没有办法保持状态还是存在?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多