在今天的开发工作当中,怎么响应长按事件(setOnItemLongClickListener)去删除一个列表项困扰了我将近一天的时间,这是初学者必须经历的。

我总结出两种方式,分享给大家参考,也希望大家能够提出自己的看法。

方法一:使用ContextMenu

*为 ListView 的所有 item 注册 ContextMenu 
*重写onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo)
*重写onContextItemSelected(MenuItem item)
*在上面的方法中定义AlertDialog.Builder对象,长按列表项的时候弹出Dialog,确定是否删除
*添加AlertDialog.Builder对象的setPositiveButton()方法和setNegativeButton()方法

方法二:使用listView.setOnItemLongClickListener()

*重写onItemLongClick()

下面通过一个例子讲解一下这两种方法的具体用法(省略了包的导入),首先,看一下我实现的效果:

UICollectionViewCell长按删除 iOS listview长按删除item_listview

方法一:使用ContextMenu

布局文件:main.xml,主activity的布局文件

<span style="font-family:Verdana;font-size:18px;color:#3333ff;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/LinearLayout1"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical"
     android:paddingBottom="@dimen/activity_vertical_margin"
     android:paddingLeft="@dimen/activity_horizontal_margin"
     android:paddingRight="@dimen/activity_horizontal_margin"
     android:paddingTop="@dimen/activity_vertical_margin"
     tools:context=".MainActivity" >
    <ListView 
        android:id="@+id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:longClickable="true"/>
</LinearLayout></span>

布局文件:simple_item.xml,列表项布局文件

<span style="font-family:Verdana;font-size:18px;color:#3333ff;"><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- 头像header -->

    <ImageView
        android:id="@+id/header"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:paddingLeft="10dp" />

    <!-- 姓名name -->

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
      android:layout_toRightOf="@id/header"
        android:paddingLeft="10dp"
        android:textColor="#f0f"
        android:textSize="20sp" />

<!--简介desc-->
    <TextView
        android:id="@+id/desc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/header"
        android:layout_below="@+id/name"
        android:paddingLeft="10dp"
        android:textSize="14sp" />
</RelativeLayout></span>

MainActivity代码:

<span style="font-family:Verdana;font-size:18px;">public class MainActivity extends ListActivity {
//名字
private String names[]=new String[]{"虎头","弄玉","李清照","李白"};
//简介
private String desc[]=new String[]{"可爱的小孩","一个擅长音乐的人","一个擅长文学的女生","一个放荡不羁的文人"};
//头像ID 在drawable中放置了四张图片,R.drawable.headerX分别是其ID
private int imageId[]=new int[]{R.drawable.header1,R.drawable.header2,R.drawable.header3,R.drawable.header4};
private ListView listView;
//定义一个列表集合
List<Map<String,Object>> listItems;
Map<String, Object> map;
//定义一个simpleAdapter,供列表项使用
SimpleAdapter simpleAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

listView=(ListView)findViewById(android.R.id.list);
//为 ListView 的所有 item 注册 ContextMenu 
this.registerForContextMenu(listView);

listItems=new ArrayList<Map<String, Object>>();
for(int i=0;i<names.length;i++)
{
   map=new HashMap<String, Object>();
   map.put("header", imageId[i]);
   map.put("personName", names[i]);
   map.put("desc", desc[i]);
   //把列表项加进列表集合
   listItems.add(map);
}

simpleAdapter=new SimpleAdapter(this, listItems, R.layout.simple_item, new String[]{"personName","header","desc"}, new int[]{R.id.name,R.id.header,R.id.desc});
listView.setAdapter(simpleAdapter);

//重写onCreateContextMenu方法
@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
menu.setHeaderTitle("选择操作");
menu.add(0,1,Menu.NONE,"发送");
menu.add(0,2,Menu.NONE,"标记为重要");
menu.add(0,3,Menu.NONE,"重命名");
menu.add(0,4,Menu.NONE,"删除");
}

//重写onContextItemSelected方法(这里我只实现了删除列表项的功能,其他功能如有需要,请自行添加)
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case 1:
// 发送...
break;
case 2:
//标记...
break;
case 3:
//重命名...
break;
case 4:
//删除列表项...
int pos=(int)listView.getAdapter().getItemId(menuInfo.position);
if(listItems.remove(pos)!=null){//这行代码必须有
System.out.println("success");
}else {
System.out.println("failed");
}
simpleAdapter.notifyDataSetChanged();
Toast.makeText(getBaseContext(), "删除此项", Toast.LENGTH_SHORT).show(); 
break;
default:
return super.onContextItemSelected(item);
}
return true;
}
}


方法二:使用listView.setOnItemLongClickListener()

public class MainActivity extends ListActivity {
	//名字
	private String names[]=new String[]{"虎头","弄玉","李清照","李白"};
	//简介
	private String desc[]=new String[]{"可爱的小孩","一个擅长音乐的人","一个擅长文学的女生","一个放荡不羁的文人"};
	//头像ID
	private int imageId[]=new int[]{R.drawable.header1,R.drawable.header2,R.drawable.header3,R.drawable.header4};
	private ListView listView;
	//定义一个列表集合
	List<Map<String,Object>> listItems;
	Map<String, Object> map;
	//定义一个simpleAdapter,供列表项使用
	SimpleAdapter simpleAdapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		listView=(ListView)findViewById(android.R.id.list);

		listItems=new ArrayList<Map<String, Object>>();
		for(int i=0;i<names.length;i++)
		{
			map=new HashMap<String, Object>();
			map.put("header", imageId[i]);
			map.put("personName", names[i]);
			map.put("desc", desc[i]);
			//把列表项加进列表集合
			listItems.add(map);
		}
		
		simpleAdapter=new SimpleAdapter(this, listItems, R.layout.simple_item, new String[]{"personName","header","desc"}, new int[]{R.id.name,R.id.header,R.id.desc});
		listView.setAdapter(simpleAdapter);

		//listView长按事件
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					final int position, long id) {
				//定义AlertDialog.Builder对象,当长按列表项的时候弹出确认删除对话框
				AlertDialog.Builder builder=new Builder(MainActivity.this);
				builder.setMessage("确定删除?");
				builder.setTitle("提示");
				
				//添加AlertDialog.Builder对象的setPositiveButton()方法
				builder.setPositiveButton("确定", new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if(listItems.remove(position)!=null){
							System.out.println("success");
						}else {
							System.out.println("failed");
						}
						simpleAdapter.notifyDataSetChanged();
						Toast.makeText(getBaseContext(), "删除列表项", Toast.LENGTH_SHORT).show();
					}
				});
				
				//添加AlertDialog.Builder对象的setNegativeButton()方法
				builder.setNegativeButton("取消", new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						
					}
				});
				
				builder.create().show();
				return false;
			}
		});
	}
}