Search code examples
androidandroid-layoutonsaveinstancestate

How to save instance state of a Layout in android


I have an activity and 5 layouts. In the onCreate I setContentView for the start page layout and then through a button i skip to another layout. The problem appears when i rotate the screen. It turns back to the start page. What I have to do to keep the same layout when I rotate the screen? This is what I have in onCreate :

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

By clicking the start button it goes to the first method :

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

.....some code and then

 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
        }
    });

then second question :

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

and so on.


Solution

  • You can save your last Activity state and reuse it when recreating the 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);
    }