【发布时间】:2016-09-19 15:36:42
【问题描述】:
我在片段中有按钮,并且我已将按钮的初始颜色设置为绿色,单击按钮后我将按钮颜色设置为红色,但是当我滑动并转到另一个片段并在第一个片段之后按钮颜色设置初始颜色不是红色请帮忙,在关闭我的应用程序并重新启动应用程序后,颜色是初始颜色。
这是我点击按钮的代码
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.table1:
btnColor = (ColorDrawable) table1.getBackground();
colorId = btnColor.getColor();
if (colorId == getResources().getColor(R.color.colorAcce)) {
String value = table1.getText().toString();
Intent intent = new Intent(getActivity(), TakeOrderActivity.class);
intent.putExtra("myString", value);
startActivity(intent);
table1.setBackgroundColor(getActivity().getResources().getColor(R.color.colorAccent));
}else
{
((MainActivity)getActivity()).navigateFragment(1);
}
break;
case R.id.table2:
btnColor = (ColorDrawable) table2.getBackground();
colorId = btnColor.getColor();
if (colorId == getResources().getColor(R.color.colorAcce)){
String value1 = table2.getText().toString();
Intent intent1 = new Intent(getActivity(), TakeOrderActivity.class);
intent1.putExtra("myString", value1);
startActivity(intent1);
table2.setBackgroundColor(getActivity().getResources().getColor(R.color.colorAccent));
}else
{
((MainActivity)getActivity()).navigateFragment(1);
}
break;
}
这是修改后的代码
public String getButtonState(int id) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
return pref.getString("btn"+id, "not_clicked");
}
public void setButtonState(int id,String state) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = pref.edit();
editor.putString("btn"+id, state);
editor.commit();
}
@Override
public void onResume() {
if(getButtonState(R.id.table1).equals("clicked")){
table1.setBackgroundColor(getActivity().getResources().getColor(R.color.colorAcce));
} else {
table1.setBackgroundColor(getActivity().getResources().getColor(R.color.colorAccent));
}
if(getButtonState(R.id.table2).equals("clicked")){
table2.setBackgroundColor(getActivity().getResources().getColor(R.color.colorAcce));
} else {
table2.setBackgroundColor(getActivity().getResources().getColor(R.color.colorAccent));
}
if(getButtonState(R.id.table9).equals("clicked")){
table9.setBackgroundColor(getActivity().getResources().getColor(R.color.colorAccent));
} else {
table9.setBackgroundColor(getActivity().getResources().getColor(R.color.colorAcce));
}
if(getButtonState(R.id.table11).equals("clicked")){
table11.setBackgroundColor(getActivity().getResources().getColor(R.color.colorAccent));
} else {
table11.setBackgroundColor(getActivity().getResources().getColor(R.color.colorAcce));
}
super.onResume();
}
【问题讨论】:
-
您必须将按钮的颜色保存在内存中的某个位置,否则 Android 不知道您是否更改了按钮颜色。
-
我可以使用共享偏好来存储颜色吗?
-
使用saveinstance保存fragmnet状态
-
@Dipak 是的,SharedPreferences 是一个很好的方法。
-
@Dipak 检查我的答案。
标签: android fragment android-tablayout