java - 如何从我的自定义基础适配器中删除项目?

标签 java android baseadapter

我正在扩展 BaseAdapter 以制作自定义 ListView 行。我有上下文菜单,每次用户按住该行时都会打开,并提示他是否要删除它。但是如何删除该行? hashmap只是测试数据。

private MyListAdapter myListAdapter;
private ArrayList<HashMap<String, String>> items;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    items = new ArrayList<HashMap<String,String>>();
    HashMap<String, String> map1 = new HashMap<String, String>();
    map1.put("date", "10/09/2011");
    map1.put("distance", "309 km");
    map1.put("duration", "1t 45min");
    items.add(map1);

    myListAdapter = new MyListAdapter(this, items);
    setListAdapter(myListAdapter);
    getListView().setOnCreateContextMenuListener(this);
}


private class MyListAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<HashMap<String, String>> items;

    public MyListAdapter(Context context, ArrayList<HashMap<String, String>> items) {
        this.context = context;
        this.items = items;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View view = convertView;

        if (view == null) {
            LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.row_log, null);
        }

        TextView rowLogOverview = (TextView) view.findViewById(R.id.rowLogOverview);

        HashMap<String, String> item = items.get(position);
        rowLogOverview.setText(item.get("date"));

        return view;
    }
}

最佳答案

您不要从适配器中删除!你从项目中删除!并且适配器位于您的项目和 View 之间。从 View 中您可以获得位置,并根据位置可以删除项目。然后适配器将刷新您的 View 。

这意味着你需要做这样的事情

 items.remove(position);
adapter.notifyDataSetChanged()

关于java - 如何从我的自定义基础适配器中删除项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7372301/

相关文章:

java - 查找图像中迷宫走廊的大小

java - Java TreeMap put() 方法的奇怪行为

安卓 : MultiChoiceModeListener not invoked inside ListFragment

java - Groovy 2.5.0 为 methodcalltransformation 提供了 noclassdeffounderror

java - 从字符串中获取正确的小时值

android - 'keystore' 的值无效。它必须解析为单一路径

Android:偏好 Activity 。列表值的依赖性

Android ADT - 禁用 "use same device for future launches"

android - 如何在扩展 BaseAdapter 的适配器中使用 onActivityResult

android - BaseAdapter 类不会在 Asynctask 中设置 Adapter - Android