屏幕旋转后如何保持按钮样式和单击状态? [英] How to maintain a button style and click state after screen rotation?

查看:43
本文介绍了屏幕旋转后如何保持按钮样式和单击状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Android上创建一个应用.用户单击按钮时,按钮的背景颜色变为红色.但是,当我旋转屏幕时,背景颜色会变回原始颜色.

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.

当用户单击按钮时,我已经使用 button.setBackgroundResource(R.drawable.button_red)将背景更改为红色.我试图使用 onSaveInstanceState(Bundle savedInstanceState)来保持相同的背景色和屏幕旋转后按钮的单击状态,但是我不知道该如何处理.

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.
    }
}

谢谢!

推荐答案

保持按钮的 onClick 发生更改的 boolean ,并将其保存在 onSaveInstanceState上喜欢

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

并在 onCreateView 上进行检查

@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.
  }
}

这篇关于屏幕旋转后如何保持按钮样式和单击状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆