android listview的创建及行删除操作
Step1:创建listview
ListView list = (ListView) findViewById(R.id.ListView01);
list.setBackgroundColor(Color.WHITE);//设置背景颜色
list.setCacheColorHint(Color.WHITE);
//生成动态数组,加入数据
listItem = new ArrayList<HashMap<String, Object>>();
map = new HashMap<String, Object>();
for(int i=0;i<10;i++)
{
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ItemImage", R.drawable.checked);//图像资源的ID 把图标放到工程的相应木来下
map.put("ItemTitle", "Level ");
map.put("ItemText", "Finished in 1 Min 54 Secs, 70 Moves!");
listItem.add(map);
}
//生成适配器的Item和动态数组对应的元素
SimpleAdapter listItemAdapter = new SimpleAdapter(this,listItem,//数据源
R.layout.list_items,//ListItem的XML实现
//动态数组与ImageItem对应的子项
new String[] {"ItemImage","ItemTitle", "ItemText"},
//ImageItem的XML文件里面的一个ImageView,两个TextView ID
new int[] {R.id.ItemImage,R.id.ItemTitle,R.id.ItemText}
);
//添加并且显示
list.setAdapter(listItemAdapter);
//添加点击
list.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
{
String item = (String)listItem.get(arg2).get("ItemTitle");
setTitle("点击第"+item);
}
});
//添加长按点击
list.setOnCreateContextMenuListener(new OnCreateContextMenuListener()
{
@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo)
{
menu.setHeaderTitle("长按菜单-ContextMenu");
menu.add(0, 0, 0, "删除审批单");
menu.add(0, 1, 0, "取消删除");
}
});
//长按菜单响应函数
@Override
public boolean onContextItemSelected(MenuItem item)
{
setTitle("点击了长按菜单里面的第"+item.getItemId()+"个项目");
int selectedPosition = ((AdapterContextMenuInfo) item.getMenuInfo()).position;//获取点击了第几行
return super.onContextItemSelected(item);
}
删除操作
listItem.remove(position);//选择行的位置
listItemAdapter.notifyDataSetChanged();
list.invalidate();
listview会删除选择的行,重新更新