我有按鈕在片段中,我已設置按鈕的初始顏色是綠色和按鈕單擊後我將按鈕顏色設置爲紅色但是當我滑動並去其他片段後來在第一個片段的按鈕顏色設置初始顏色不是紅色請幫助,也是在關閉我的應用程序並重新啓動應用程序的顏色是初始顏色。設置按鈕背景顏色在按鈕單擊後的片段
這是我的代碼對於按鈕,點擊
@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不知道你是否改變了按鈕的顏色。 –
我可以使用共享首選項來存儲顏色。 – Dipak
使用saveinstance保存fragmnet狀態 –