安卓:使用AlertDialog当从列表视图中的项目是漫长的pressed [英] Android: using AlertDialog when an item from a listview is long pressed
问题描述
我有一个项目列表,通过列表视图创建。我想长preSS列表中的项目和一个警告对话框中的一个开拓并根据是或在该对话框中我婉设置一个全局变量没有钥匙。在code,我现在用的就是里面的MyActivity.java,看起来像这样:
I have a list of items, created by a listview. I would like to long press one of the items on the list and an alert dialog to open up and depending on yes or no key on that dialog box I wan to set a global variable. The code that I am using is inside "MyActivity.java" and looks like this:
ListView lv = getListView();
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> av, View v, int pos, final long id) {
final AlertDialog.Builder b = new AlertDialog.Builder(MyActivity.this);
b.setIcon(android.R.drawable.ic_dialog_alert);
b.setMessage("Are you sure?");
b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
yesOrNo = 1;
}
});
b.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
yesOrNo = 0;
}
});
b.show();
if (yesOrNo == 1) {
DO SOMETHING;
}
return true;
}
});
不过,全局变量yesOrNo是不会改变,无论我是否preSS是或否。
有人可以让我知道什么是错的code?
However, the global variable "yesOrNo" is not changing no matter if I press "Yes" or "No". Can somebody let me know what is wrong with the code?
感谢您的帮助。
推荐答案
AlertDialog
不等待选择。在调用显示()
方法,这两条线将立即执行:
AlertDialog
does not wait for the selection. After you call show()
method, these two lines will be executed immediately:
if (yesOrNo == 1) {
DO SOMETHING;
}
所以 yesOrNo
变量的值将是其初始值。
So value of yesOrNo
variable will be its initial value.
解决方案
您可以致电 DoSomething的(0)
在的onClick()
positiveButton的方法和 DoSomething的(1)
在的onClick()
negativeButton的方法。
You can call doSomething(0)
in onClick()
method of positiveButton and doSomething(1)
in onClick()
method of negativeButton.
这篇关于安卓:使用AlertDialog当从列表视图中的项目是漫长的pressed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!