Android:具有多个可点击按钮的 ListView 元素 [英] Android: ListView elements with multiple clickable buttons

查看:27
本文介绍了Android:具有多个可点击按钮的 ListView 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ListView,其中列表中的每个元素都包含一个 TextView 和两个不同的按钮.像这样:

I've a ListView where every element in the list contains a TextView and two different Buttons. Something like this:

ListView
--------------------
[Text]
[Button 1][Button 2]
--------------------
[Text]
[Button 1][Button 2]
--------------------
... (and so on) ...

使用此代码,我可以为整个项目创建一个 OnItemClickListener:

With this code I can create an OnItemClickListener for the whole item:

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> list, View view, int position, long id) {
        Log.i(TAG, "onListItemClick: " + position);

        }

    }
});

但是,我不希望整个项目都可以点击,而只希望每个列表元素的两个按钮都可以点击.

However, I don't want the whole item to be clickable, but only the two buttons of each list element.

所以我的问题是,如何使用以下参数为这两个按钮实现 onClickListener:

So my question is, how do I implement a onClickListener for these two buttons with the following parameters:

  • int button(点击了元素的哪个按钮)
  • int position(列表中发生按钮点击的元素)
  • int button (which button of the element has been clicked)
  • int position (which is the element in the list on which the button click happened)

更新:我找到了如下答案中所述的解决方案.现在我可以通过触摸屏点击/点击按钮.但是,我无法使用轨迹球手动选择它.它总是选择整个列表项,然后从那里直接转到下一个列表项而忽略按钮,即使我设置了 .setFocusable(true)setClickable(true)getView() 中的按钮.

Update: I found a solution as described in my answer below. Now I can click/tap the button via the touch screen. However, I can't manually select it with the trackball. It always selects the whole list item and from there goes directly to the next list item ignoring the buttons, even though I set .setFocusable(true) and setClickable(true) for the buttons in getView().

我还将此代码添加到我的自定义列表适配器中:

I also added this code to my custom list adapter:

@Override
public boolean  areAllItemsEnabled() {
    return false;           
}

@Override
public boolean isEnabled(int position) {
        return false;
}

这会导致不再有任何列表项可供选择.但这无助于使嵌套按钮可选.

This causes that no list item is selectable at all any more. But it didn't help in making the nested buttons selectable.

有人有想法吗?

推荐答案

这个问题的解决方案实际上比我想象的要容易.您可以简单地在您的自定义适配器的 getView() 方法中为您正在使用的按钮添加一个 setOnClickListener().

The solution to this is actually easier than I thought. You can simply add in your custom adapter's getView() method a setOnClickListener() for the buttons you're using.

任何与按钮相关的数据都必须用 myButton.setTag() 添加到 getView() 中,并且可以通过 view 在 onClickListener 中访问.getTag()

Any data associated with the button has to be added with myButton.setTag() in the getView() and can be accessed in the onClickListener via view.getTag()

我在我的博客上发布了详细的解决方案 作为教程.

这篇关于Android:具有多个可点击按钮的 ListView 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆