Question

I am trying creating an app on Android. When a user click on a button, the background color of the button changes to red. However, when I rotate the screen, the background color changes back to the original color.

I've used button.setBackgroundResource(R.drawable.button_red) to change the background to red when the user clicked on the button. I am trying to use onSaveInstanceState(Bundle savedInstanceState) to maintain the same background color and clicked state of the button after the screen rotation, but I don't know how to approach this.

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putBoolean(ANSWER_ONE_BUTTON_ISCLICKED, true);
    super.onSaveInstanceState(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
        Bundle savedInstanceState) {
    if (savedInstanceState != null) {
       button.setBackgroundResource(R.drawable.button_red);
       //some codes to make the button becomes clicked.
    }
}

Thanks!

Was it helpful?

Solution

Maintain a boolean that changes on the onClick of the button and save it on onSaveInstanceState like

@Override
public void onSaveInstanceState(Bundle savedInstanceState) 
{
  savedInstanceState.putBoolean(ANSWER_ONE_BUTTON_ISCLICKED, isButtonOneClicked);
  super.onSaveInstanceState(savedInstanceState);
}

and on onCreateView check like this

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
    Bundle savedInstanceState) 
{
  if (savedInstanceState != null) 
  {
    if (savedInstanceState.containsKey(ANSWER_ONE_BUTTON_ISCLICKED))
    {
      if (savedInstanceState.getBoolean(ANSWER_ONE_BUTTON_ISCLICKED))
        button.setBackgroundResource(R.drawable.button_red);
      else
        button.setBackgroundResource(R.drawable.original_color);
    }
     //some codes to make the button becomes clicked.
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top