tabhost 中的共享首选项不适用于按钮按下状态。
我正在按下状态下更改按钮的背景。但是当我重新启动(关闭和打开)手机时,共享首选项不会保存状态。
变量
btn_state
在下面的行中总是返回 False
final boolean btn_state = prefs.getBoolean("BUTTON_STATE", isclick);
任何帮助总是很感激,谢谢
这是我的代码
private SharedPreferences prefs;
private String prefName = "MyPref";
private SharedPreferences.Editor editor;
private static final String BUTTON_STATE = "button_selected";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
final boolean btn_state = prefs.getBoolean("BUTTON_STATE", isclick);
editor = prefs.edit();
if(btn_state == false){
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
}
else if(btn_state == true){
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
}
}
@Override
public void onStop() {
super.onStop();
prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
editor = prefs.edit();
editor.putBoolean("BUTTON_STATE", isclick);
editor.commit();
}
public static boolean isclick = false;
private View.OnClickListener listner1 = new View.OnClickListener() {
public void onClick(View v) {
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
isclick = true;
prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
editor = prefs.edit();
editor.putBoolean("BUTTON_STATE", isclick);
editor.commit();
} else {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
isclick = false;
}
isclick = !isclick;
}
编辑
private boolean isclick ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) { isclick = false; }
prefs = this.getSharedPreferences(prefName, MODE_PRIVATE);
isclick = prefs.getBoolean("prefName", false);
System.out.println("bool? " + isclick);
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
} else if (!isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
}
}
@Override
public void onRestart() {
super.onRestart();
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
} else if (!isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
}
}
@Override
public void onStop() {
super.onStop();
prefs = this.getSharedPreferences(prefName, MODE_PRIVATE);
editor = prefs.edit();
editor.putBoolean("prefName", true);
editor.commit();
}
private View.OnClickListener listner1 = new View.OnClickListener() {
public void onClick(View v) {
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
editor = prefs.edit();
editor.clear();
editor.putBoolean("prefName", true);
editor.commit();
} else if (!isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
editor = prefs.edit();
editor.clear();
editor.putBoolean("prefName", false);
editor.commit();
}
isclick = !isclick;
}
};