Android:在 ListView 的 onItemClick 事件中使用 AlertDialog
我有一个使用 ListActivity 的 Android 应用程序。单击列表中的项目时,我想向用户显示一个确认对话框,然后对单击的项目执行一些操作。
但是,从对话框的 onClick 处理程序中,我无法从列表 onClick 事件中访问位置变量,因此我无法判断用户单击了哪个项目。
这是我想要实现的一个示例:
getListView().setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
// This doesn't work, can't access position from here
Object o = MyListActivity.this.getListView().getItemAtPosition(position);
testFunction(o);
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(MyListActivity.this);
builder.setMessage("Are you sure you want to do this?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
});
我想我可以通过将信息存储在活动的成员变量中来传递信息,但似乎应该有更好的解决方案!谁能告诉我正确/合理的方法来做到这一点?
谢谢, 安迪
I have an Android app using ListActivity. When an item in the list is clicked, I'd like to display a confirmation dialog to the user, then perform some action on the clicked item.
However, from the dialog's onClick handler, I can't access the position variable from the list onClick event so I can't tell which item the user clicked.
Here's an example of what I'm trying to achieve:
getListView().setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
// This doesn't work, can't access position from here
Object o = MyListActivity.this.getListView().getItemAtPosition(position);
testFunction(o);
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(MyListActivity.this);
builder.setMessage("Are you sure you want to do this?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
});
I suppose I could pass the information in by storing it in a member variable on the Activity, but it seems like there should be a better solution! Can anyone fill me in on the correct/sensible way to do this?
Thanks,
Andy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不确定这是否是执行此操作的“正确”方法,但您可以这样做:
然后在处理程序中使用“InternalPosition”
不确定这是否适用于您的情况,但我知道您可以从访问“最终”变量听者。
Not sure if this is the "correct" way to do this or not but you could do this:
And then in your handler use 'InternalPosition'
Not sure if this will work in your case but I know you can access 'final' variables from the listener.