Android開發:ListView 長按刪除列表項兩種方式
阿新 • • 發佈:2019-02-17
在今天的開發工作當中,怎麼響應長按事件(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()
下面通過一個例子講解一下這兩種方法的具體用法(省略了包的匯入),首先,看一下我實現的效果:
方法一:使用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;
}
});
}
}