我目前正在嘗試創建一個'切換'類型的按鈕,其中如果某個布爾值爲'true',則會彈出AlertDialog,而如果爲false,則不會彈出對話框。如何繼續收聽onClick?
但是,問題在於目前只有當活動開始時才改變按鈕的行爲,而不是實際改變布爾值時。
我認爲這是因爲我已經把這個方法放在了onStart上,儘管我不太確定把代碼放在哪裏。
我如何不斷收聽onClick,以便在用戶更改設置後立即更改按鈕?下面
是我當前的代碼:
public void onStart() {
super.onStart();
final SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
final SharedPreferences.Editor editor = settings.edit();
final Button StopButton = (Button) findViewById(R.id.StopButton);
boolean RequestingLU = settings.getBoolean("RequestingLU", true);
if (RequestingLU) {
StopButton.setText(R.string.Stop_Button);
StopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder StopDialog = new AlertDialog.Builder(MainMenu.this);
StopDialog.setTitle(R.string.Stop_Title);
StopDialog.setMessage(R.string.Stop_Message);
StopDialog.setPositiveButton(R.string.Stop_Button, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
editor.putBoolean("RequestingLU", false);
editor.apply();
Toast.makeText(MainMenu.this, "You have stopped the app", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
StopDialog.setNeutralButton(R.string.Negative_Button, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Closes box
dialog.dismiss();
}
});
StopDialog.create().show();
}
});
}
else {
StopButton.setText(R.string.Start_Button);
StopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
editor.putBoolean("RequestingLU", true);
editor.apply();
Toast.makeText(MainMenu.this, "You have started the app", Toast.LENGTH_SHORT).show();
}
});
}
}
嘗試在的onResume /的onCreate –
的onResume? AlertDialog關閉時調用onResume嗎? –
使其在oncreate –