1

我已经花了很多时间试图解决这个问题,我已经看到了很多关于这个主题的其他 StackOverflow 帖子,但我找不到适合我的解决方案。

我有一个 ListActivity 和一个自定义 ArrayAdapter。我的列表视图中有几个按钮,例如删除按钮。但是,只有在单击列表的 TextView 时才会调用 onItemClick 方法。我可以将 OnClickListeners 添加到按钮,但是我遇到的问题是我不知道按钮所属元素的位置。我知道我可以为每个按钮设置标签,但必须有更好的方法!

这是我的适配器:

    private class ItemListAdapter extends ArrayAdapter<Item> {
    private ArrayList<Item> items;
    private int countItems = 0;

    public ItemListAdapter(Context ctx, int textViewResourceId, ArrayList<Item> itemList){
        super(ctx, textViewResourceId, itemList);
        this.items = itemList;  
        this.countItems = itemList.size();
    }

    public int getCount(){
        return countItems;
    }

    public Item getItem(int pos){
        return itemList.get(pos);
    }

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

        //Get the current list item
        final Item currentItem = itemList.get(position);

        if (row == null) {
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = vi.inflate(R.layout.itemlist_item_row, null);
        }
        Item item = items.get(position);
        if (item != null){
            TextView bt = (TextView) row.findViewById(R.id.bt_itemlist_item);
            if (bt != null){
                bt.setText(item.getName());
            }
        }
        return row;
    }

}

如果有人能告诉我最好的解决方案,那就太好了。

4

3 回答 3

0

设置OnClickListenersfor Buttonsin getView(),您将获得职位

于 2012-12-03T16:26:14.443 回答
0

就像您执行 bt.setText(item.getName()) 一样,为什么不获取对删除按钮的引用,然后为其设置点击监听器。您将在 getView 方法中添加 on click 侦听器,您将自动获取行的位置。

于 2012-12-03T16:26:50.260 回答
0

这是一种方法。设置视图的标签很常见,但如果您不想设置许多视图的标签,只需使用父视图(如果可能)。对于row您返回的变量,将标签设置为您的 Item, currentItem。否则,只需设置每个可点击视图的标签。

对于每个单击操作,您实际上可以使用 1 个单击侦听器实例,并且只需检查视图父级的标记。例如,View.OnClickListener为布局中的每个删除按钮创建 1 个实例。在该onClick()方法中,查看父View的标签,获取Item应该删除的实例。

private class ItemListAdapter extends ArrayAdapter<Item>
{

    View.OnClickListener deleteListener = new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            View parent = (View)view.getParent();
            Item item = (Item)parent.getTag();
            //Do something with "item"
        }
    };

    //Remainder omitted

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

        //Remainder omitted
        row.setTag(currentItem);
        View deleteButton; //find this somewhere in your layout
        deleteButton.setOnClickListener(deleteListener);

        return row;
    }

}
于 2012-12-03T16:27:08.043 回答