搭建直播平台,Android ListView 长按删除列表项
一、核心代码
监听器 - 长按弹出对话框 AdapterView.OnItemLongClickListener
private final AdapterView.OnItemLongClickListener itemDeleteListener = new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
// 确认删除对话框构建
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("确认删除?");
// 点击对话框的 确认 按钮后的操作
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
numList.remove(position); // 从 numList 中删除点击的列表项
adapter.notifyDataSetChanged(); // 适配器数据刷新
Toast.makeText(getBaseContext(), "已删除", Toast.LENGTH_SHORT).show();
}
});
// 点击对话框的 取消 按钮后的操作
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 无操作
}
});
builder.create().show();
return false;
}
};
绑定监听器
// 绑定监听器
listView.setOnItemLongClickListener(itemDeleteListener);
二、全部代码
1、XML
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="@+id/num_list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/item_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:layout_centerHorizontal="true"
android:text="number"
android:textSize="30sp" />
</RelativeLayout>
以上就是 搭建直播平台,Android ListView 长按删除列表项,更多内容欢迎关注之后的文章