androidlayoutactivity-lifecycle

Keeping TextView visibility (View.INVISIBLE) and Button state (setEnabled(false)) after screen rotation


I have an app with a Button to show the answer of a question asked. And a TextView with a warning text and another empty one that displays the answer when the button is clicked. When the user clicks the button, I want the warning textView to disappear and the button to be "unclickable". I managed to achieve this and everything worked as intended, but the problem occurs when I rotate the screen, nothing stays the same. The code below is in onCreate().

Button buShowAnswer = findViewById(R.id.buShowAnswer);
TextView tvShownAnswer = findViewById(R.id.tvShownAnswer);
TextView tvWarning = findViewById(R.id.tvWarning);

buShowAnswer.setOnClickListener((View v) -> {
        String answer;
        if (isAnswerTrue){
            answer = getString(R.string.true_answer);
        }else {
            answer = getString(R.string.false_answer);
        }
        tvWarning.setVisibility(View.INVISIBLE);
        buShowAnswer.setEnabled(false);
        tvShownAnswer.setText(answer);
        cheatState = true;
    });

Solution

  • You should use onSaveInstanceState to save the state of your local variable when the screen is rotated, then use the saved value in onCreate (which is called upon rotation to create the new rotated activity).

    So add this function

    private boolean cheatState = false;
    private static final String CHEAT_STATE = "CHEAT_STATE";
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putBoolean(CHEAT_STATE, cheatState);
    
        // call superclass to save any view hierarchy
        super.onSaveInstanceState(outState);
    }
    

    and in your onCreate you can then call

    if (savedInstanceState != null) {
        cheatState = savedInstanceState.getBoolean(CHEAT_STATE);
        if( cheatState ) {
            buShowAnswer.setEnabled(false);
            tvWarning.setVisibility(View.INVISIBLE);
        }
    }