安卓ListView里onItemClick如何添加AlertDialog
时间: 2024-01-24 10:01:56 浏览: 155
在onItemClick方法中添加AlertDialog的步骤如下:
1. 创建AlertDialog.Builder对象
```
AlertDialog.Builder builder = new AlertDialog.Builder(context);
```
2. 设置AlertDialog的标题、消息内容和按钮
```
builder.setTitle("提示");
builder.setMessage("确定要删除该项吗?");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 确定按钮的点击事件
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 取消按钮的点击事件
}
});
```
3. 创建AlertDialog对象并显示
```
AlertDialog dialog = builder.create();
dialog.show();
```
完整的示例代码如下:
```
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("提示");
builder.setMessage("确定要删除该项吗?");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 确定按钮的点击事件
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 取消按钮的点击事件
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
```
阅读全文