我有一个基本的警报对话框,该对话框在我第一次加载应用程序时运行。当在我的“ onOptionsItemSelected”中选择一个选项时,将弹出警报。它加载时间列表,并且默认情况下将“ 30秒”选择为“ 4”。
但是说用户只是打开它,并且不更改任何设置,然后单击“确定”,“它”应该使我的“ notificationChoice”为4,除了使它为0。直到我实际选择一个位置“它”将返回0。按下“确定”,重新打开通知,然后单击“确定”,我将从“哪个”中获得正确的结果。这是故意的还是我做错了什么?
private void changeNotificationTimer() {
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(this);
String[] timeModes = { "10 Seconds.", "15 Seconds.", "20 Seconds.",
"25 Seconds.", "30 Seconds.", "45 Seconds.", "1 Minute." };
final int timerPos = settings.getInt("timerPos", 4);
System.out.println("timerPos : " + timerPos);
// Where we track the selected item
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Set the dialog title
builder.setTitle("Set Notification Timer");
// Lets set up the single choice for the game mode.
builder.setSingleChoiceItems(timeModes, timerPos,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
notificationChoice = which;
System.out.println("which : " + which);
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.out.println("notificationChoice : " + notificationChoice);
// Set the shared prefs.
if (timerPos != notificationChoice) {
System.out.println(timerPos + " != " + notificationChoice);
setSharedNotificationPrefs(notificationChoice);
}
}
}).create().show();
}
最佳答案
没有。
单击对话框上的选项时,会触发onClick(DialogInterface, int)
。用户按下肯定按钮时不会触发它。
我猜想显示对话框时,notificationChoice是0
,因此timerPos != notificationChoice
通过并保存了0。在显示对话框之前,应将notificationChoice
设置为timerPos
。并且无需检查timerPos != notificationChoice
。只需保存notificationChoice
。
notificationChoice = timerPos;
builder.setSingleChoiceItems(timeModes, timerPos,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
notificationChoice = which;
System.out.println("which : " + which);
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.out.println("notificationChoice : " + notificationChoice);
// Set the shared prefs.
System.out.println(timerPos + " != " + notificationChoice);
setSharedNotificationPrefs(notificationChoice);
}
}).create().show();