安卓:ListView的元素有多个可单击按钮多个、单击、按钮、ListView

2023-09-11 10:28:39 作者:小活祖宗

我有一个的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) ...

通过这个code,我可以创建一个 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按钮(该元素的按钮被点击) INT位置(这是在其上单击按钮发生了列表中的元素) 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(真) setClickable(真) 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().

我还添加了这code到我的自定义列表适配器:

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()并且可以在onClickListener通过 view.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()

我贴在我的博客作为教程。

 
精彩推荐
图片推荐