如何在android中保存Layout的实例状态

时间:2017-05-09 17:49:52

标签: android android-layout onsaveinstancestate

我有一个活动和5个布局。 在onCreate中我使用setContentView作为起始页面布局,然后通过一个按钮跳转到另一个布局。旋转屏幕时出现问题。它会回到起始页面。旋转屏幕时我需要做些什么才能保持相同的布局? 这就是我在onCreate中所拥有的:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(**R.layout.activity_main**);

单击开始按钮,转到第一种方法:

public void firstQuestion(View view) {
    //here we change the layout. it will be the same for every new question
    setContentView(**R.layout.first_question**);

.....一些代码然后

 final ImageView forward = (ImageView) findViewById(R.id.forward);
    forward.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (time_is_up) resultsDialog(view);//if time is up we jump to results
            else secondQuestion(view);          //if not we skip to the next question
        }
    });

然后第二个问题:

public void secondQuestion(View view) {
    setContentView(**R.layout.second_question**);

等等。

1 个答案:

答案 0 :(得分:0)

您可以保存上次活动状态,并在重新创建活动时重复使用它:

int layoutId = R.layout.activity_main;

@Override
public void onSaveInstanceState(Bundle outState) {
   outState.putInt("layoutId", layoutId);
   super.onSaveInstanceState(outState);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        layoutId = savedInstanceState.getInt("layoutId", R.layout.activity_main);
    }
    setContentView(layoutId);
}

public void firstQuestion(View view) {
    layoutId = R.layout.first_question;
    setContentView(layoutId);
}