タブホスト内の共有設定が、ボタンが押された状態で機能しない。
押された状態のボタンの背景を変更しています。しかし、電話を再起動すると(オフとオン)、共有設定は状態を保存しません。
変数
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;
}
};