当用户在AlertDialog中单击“确定”时,我想将变量传递给外部函数。 我正在尝试这个例子,但它不会识别变量(Yup)。
public final void deleteBookmark(Cursor cur, int pos) {
//fetching info
((Cursor) cur).moveToPosition(pos);
String bookmark_id = ((Cursor) cur).getString(((Cursor) cur).getColumnIndex(Browser.BookmarkColumns._ID));
String bookmark_title = ((Cursor) cur).getString(((Cursor) cur).getColumnIndex(Browser.BookmarkColumns.TITLE));
//asking user to approve delete request
AlertDialog alertDialog = new AlertDialog.Builder(Dmarks.this).create();
alertDialog.setTitle("Delete" + " " + bookmark_title);
alertDialog.setIcon(R.drawable.icon);
alertDialog.setMessage("Are you sure you want to delete this Bookmark?");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
**String Yup = "yes";**
} });
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Context context = getApplicationContext();
Toast.makeText(context, "canceled" , Toast.LENGTH_SHORT).show();
} });
alertDialog.show();
**if (Yup == "yes")** {
//deleting if user approved
getContentResolver().delete(Browser.BOOKMARKS_URI, "_id = " + bookmark_id, null);
//notifying user for deletion
Context context = getApplicationContext();
Toast.makeText(context, bookmark_title + " " + "deleted" , Toast.LENGTH_SHORT).show();
}
}
我知道代码有点乱,但这只是为了理解。
感谢帮助!
答案 0 :(得分:5)
由于您在onClick方法中创建了字符串,因此无法识别Yup,并且在onClick完成后它将被回收。
我建议摆脱Yup,因为即使你解决了这个问题,你也会遇到问题。该对话框将弹出,但是当用户选择时,应用程序将已经通过if语句,因此Yup从未有机会等于“是”。换句话说,在通过“if(Yup ==”yes“)之前,对话框不会暂停代码并等待用户输入。此外,if语句应如下所示:if (Yup.equals("yes"))
,否则,它每次都会返回false。
我会让你的代码看起来像这样:
public final void deleteBookmark(Cursor cur, int pos) {
//fetching info
((Cursor) cur).moveToPosition(pos);
final String bookmark_id = ((Cursor) cur).getString(((Cursor) cur).getColumnIndex(Browser.BookmarkColumns._ID));
final String bookmark_title = ((Cursor) cur).getString(((Cursor) cur).getColumnIndex(Browser.BookmarkColumns.TITLE));
//asking user to approve delete request
AlertDialog alertDialog = new AlertDialog.Builder(Dmarks.this).create();
alertDialog.setTitle("Delete" + " " + bookmark_title);
alertDialog.setIcon(R.drawable.icon);
alertDialog.setMessage("Are you sure you want to delete this Bookmark?");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//deleting if user approved
getContentResolver().delete(Browser.BOOKMARKS_URI, "_id = " + bookmark_id, null);
//notifying user for deletion
Context context = getApplicationContext();
Toast.makeText(context, bookmark_title + " " + "deleted" , Toast.LENGTH_SHORT).show();
} });
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Context context = getApplicationContext();
Toast.makeText(context, "canceled" , Toast.LENGTH_SHORT).show();
} });
alertDialog.show();
}
}