このような単純な警告ダイアログのコードがあります。
これが私のコードです:
private boolean toggle;
//an onCreate method here
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.deleteContact:
if (selectedContactIndex == -1){
Context context = getApplicationContext();
CharSequence text = "Please select a contact to delete!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
return true;
}
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this, AlertDialog.THEME_DEVICE_DEFAULT_DARK);
myAlertDialog.setTitle(" Confirm Contact Deletion");
myAlertDialog.setMessage("Are you sure you want to delete " + Contact.contactList.get(selectedContactIndex).getFullName() + "?");
myAlertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
toggle = true;
}});
myAlertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
toggle = false;
}});
myAlertDialog.show();
System.out.println(toggle);
if (toggle) {
Contact.contactList.remove(selectedContactIndex);
for (int i = selectedContactIndex; i < Contact.contactList.size(); i++){
Contact.contactList.get(i).setContactNumber(i);
}
Contact.totalContacts--;
selectedContactIndex = -1;
contactsView.invalidateViews();
}
}
だから私がやった方法は、トグルという名前のブール値を持っているということです。ユーザーが [はい] をクリックすると、ブール値が true に設定され、if ステートメントが実行されて実際に連絡先が削除されます。system.out.print を使用してログ cat を確認しましたが、[はい] ボタンをクリックした後でもトグル変数が false になっているようです。
私が持っている 1 つの仮説は次のとおりです。ブール値のデフォルト値は false であるため、onClick メソッドはトグルに何も割り当てていない可能性があります。しかし、これを修正する方法がわかりません。
どんな助けでも大歓迎です。
編集:答えてくれてありがとう、連絡先削除ロジックをポジティブボタンのonClickメソッドに入れました。それは私が望むように機能しています! ここから得た主なことは、Android が常に線形に実行されるとは限らないことを認識することです。