编程语言
首页 > 编程语言> > java – 如何从自定义基本适配器中删除项目?

java – 如何从自定义基本适配器中删除项目?

作者:互联网

我正在扩展BaseAdapter以创建自定义列表视图行.我有上下文菜单,每当用户持有该行时会打开,并提示他是否要删除它.但是我该如何删除该行? 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;
    }
}

解决方法:

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

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

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

标签:android,java,baseadapter
来源: https://codeday.me/bug/20191001/1838009.html