ListView需要删除
参考资料
SimpleAdapter listItemAdapter; // ListView的适配器
ArrayList<HashMap<String, Object>> listItem; // ListView的数据源,这里是一个HashMap的列表
ListView myList; // ListView控件
然后在Activity的onCreate函数中对变量进行初始化:
listItem = new ArrayList<HashMap<String, Object>>();
listItemAdapter = new SimpleAdapter(this, listItem, R.layout.mylayout,
new String[]{"image", "title", "text"},
new int[]{R.id.ItemImage, R.id.ItemTitle, R.id.ItemText});
myList = (ListView)findViewById(R.id.TaxiList);
myList.setAdapter(listItemAdapter);
添加两个私有的功能函数:
private void addItem()
{
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("image", R.drawable.icon);
map.put("title", "标题");
map.put("text", "要显示的内容");
listItem.add(map);
listItemAdapter.notifyDataSetChanged();
}
private void deleteItem()
{
int size = listItem.size();
if( size > 0 )
{
listItem.remove(listItem.size() - 1);
listItemAdapter.notifyDataSetChanged();
}
}
另附上ListView的项自定义的Layout不再多说:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:paddingBottom="4dip"
android:paddingLeft="12dip"
android:paddingRight="12dip">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/taxi1"
android:id="@+id/ItemImage"
android:paddingTop="4dip">
</ImageView>
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="DaZhong Taxi Corporation"
android:layout_toRightOf="@+id/ItemImage"
android:id="@+id/ItemTitle"
android:textSize="24dip"></TextView>
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="Tel:021-67786874"
android:id="@+id/ItemText"
android:layout_below="@+id/ItemTitle"
android:layout_toRightOf="@+id/ItemImage">
</TextView>
</RelativeLayout>
写了一个listview 每行有一个删除按钮,用于删除这一行。删除按钮的click事件是在adapter里实现的 @Override
此时会重新调用getView方法 @Override 因为这里的复用机制,所以判断convertView为空时才创建新的行view,此时实际效果是删除了第一行元素(只是视图错乱,数据没有问题),我想是应该removeView来删除这个view来防止上面的问题,但如何获得这个view呢 待验证方式:根据button的tag记下此行的index,从传递过来的listview删除掉此view |