繁体   English   中英

Android xml布局根据方向更改

[英]Android xml layout changes upon orientation

当按下某个按钮时,从activity_main开始的xml布局将更改为graphing

public void onClick(DialogInterface dialog, int which) {
    mode = selectedMode;

    if (mode.equals("Graphing"))
    {
        setContentView(R.layout.graphing);
    }
}

但是,当用户处于该布局中并更改方向时, graphing布局将恢复为activity_main 令人不安的问题是,我既有layout所需的布局,又有layout-land

XML

layout
    activity_main
    graphing
layout-land
    activity_main
    graphing

为什么不尝试保存实例状态:

@Override

protected void onSaveInstanceState(Bundle state) {

    super.onSaveInstanceState(state);

   /*this line here save that the current orientation is landascepe */
     state.putChar('O','L'); 

}

然后检查捆绑包是否为空,如果捆绑包是空的,那么如果没有捆绑,则不进行身份验证,那么您将获得保存在好友中的内容,如下所示:

/* here you point to the id of the landscape layout */
     int mode = R.layout.graphing; 

     @Override

     protected void onCreate(Bundle bundle) {

          super.onCreate(bundle);

          if ((bundle != null)

                  && (bundle.getChar('O') != null)) {
              View v=(View)findViewById(mode);
              setContentView(v);

          }

       }

您可以参考此链接,它们非常有用:

http://developer.android.com/reference/android/os/Bundle.html

http://developer.android.com/reference/android/view/View.html

“方向更改会从onCreate引发Activity生命周期回调”,并且您在onCreate中将布局设置为activity_main ,并且当用户更改方向时,将触发onCreate并将布局设置为activity_main 正如@Mhmd Salem所说,您可以使用public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState)protected void onRestoreInstanceState(Bundle savedInstanceState)来保存和检索活动状态

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM