我正在尝试在Android上创建应用。当用户单击按钮时,按钮的背景颜色变为红色。但是,当我旋转屏幕时,背景颜色会变回原始颜色。
当用户点击按钮时,我使用button.setBackgroundResource(R.drawable.button_red)
将背景更改为红色。我试图在屏幕旋转后使用onSaveInstanceState(Bundle savedInstanceState)
来保持相同的背景颜色并单击按钮的状态,但我不知道如何处理它。
@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.
}
}
谢谢!
答案 0 :(得分:0)
维护boolean
更改按钮的onClick
并将其保存在onSaveInstanceState
上
@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.
}
}