如何将按钮放置在可展开列表视图中的组项内?

8
我正在开发一个Android应用程序。
如何将一个按钮放在ExpandableListView的一个分组中?
点击按钮后,应该显示一个对话框,而不是打开或关闭分组。在按钮外面点击时,分组应该正常打开和关闭。
下面的图像显示了我想插入按钮的位置。

http://img193.imageshack.us/img193/2060/expandablelistviewbutto.png


你已经解决了这个问题了吗? - modabeckham
4个回答

26

Android可扩展列表视图(ExpandableListView)可以在组或子项中有任何按钮。

请确保适配器中的按钮不可聚焦,如下所示。

editButton.setFocusable(false);

这将有助于单独点击组和组父元素内的按钮。


是的,这应该是答案。 - Yasitha Waduge
9
重要的是在代码中实现它,而不是使用XML。有效地工作,感谢分享。 - Damian Walczak
与我遇到同样的问题。带有标题布局的复选框不会展开/折叠。添加了这行代码后就像神奇般地工作了。 - Ranjithkumar

2
您需要使用包含按钮的自定义XML文件(例如inflate_xml_groupview.xml)来填充groupView:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/FrameLayoutGroupView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">


    <Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ButtonOfMyExpandableListGroupView"
        android:visibility="visible" />

</FrameLayout>

接下来您需要创建一个自定义的ExpandableListAdapter,它继承了BaseExpandableListAdapter,在getGroupView()方法中获取Button,代码如下:

public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {

        convertView = inflater.inflate(R.layout.inflate_xml_groupview, null);
        holder = new ViewHolder();
        holder.Button = (Button) convertView.findViewById(R.id.myButton);
        convertView.setTag(holder);
        } else {
        holder = (ViewHolder) convertView.getTag();
        }
        holder.position = ListOfItems.get(groupPosition).getPosition();
        Button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Toast.makeText(getApplicationContext(), "Button " + groupPosition + " is clicked !", Toast.LENGTH_SHORT).show();
               // DO STUFF
        }
    });
}

希望这有所帮助。

完整的示例很好,但是您忘记将android:focusable="false"属性添加到按钮中。没有这个属性它就无法工作。 - ZP007

1
为提供基于XML的解决方案,您只需将以下行添加到控件中。 android:focusable="false" 示例:
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="false"/>

0

我创建了自己的ExpandableListView。我使用XML布局和类来构建组件。

令人惊讶的是,这非常容易做到。

与标准的ExpandableListView相比,它更容易理解,因为我为列表的每个元素(列表本身、组和项)创建了一个类和一个布局。没有必要搞乱列表的列表,这在我看来会降低代码的表达力和可读性。

此外,该列表变得非常灵活和可定制。我可以轻松地在运行时添加和删除组和项。现在我可以自由修改列表的外观和内部组件。

我创建的ExpandableListView可以做到与标准相同甚至更多。只是无法确定性能是否受到影响,但没有注意到任何明显的问题。


你是怎么把按钮放进去并让它工作的?我遇到了这个问题,但是想不出解决方案。http://stackoverflow.com/questions/11205052/button-in-a-row-in-expandablelistview - noloman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接