Android xml布局在方向上发生变化

时间:2015-07-30 18:44:28

标签: java android xml android-layout

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

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

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

但是当用户处于该布局并更改方向时,graphing布局将恢复为activity_main。令人不安的问题是我有layoutlayout-land的必要布局。

XML

layout
    activity_main
    graphing
layout-land
    activity_main
    graphing

2 个答案:

答案 0 :(得分:0)

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

@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

答案 1 :(得分:0)

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