0

我有一个活动和 5 个布局。在 onCreate 中,我为起始页布局设置了内容视图,然后通过一个按钮跳到另一个布局。当我旋转屏幕时出现问题。它返回到起始页。当我旋转屏幕时,我必须做些什么来保持相同的布局?这就是我在 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**);

等等。

4

1 回答 1

1

您可以保存上一个 Activity 状态并在重新创建 Activity 时重用它:

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);
}
于 2017-05-09T19:17:45.050 回答