Android 可扩展列表视图带有按钮的父项

6
我正在尝试实现类似于以下示例的功能。可扩展列表由某些类别名称组成,当单击父项时,它会显示该类别中所有子项的列表。 现在,假设我想动态地向任何类别添加一个子项目? 我该怎么做? 我是否需要在列表中的每个父项旁边保留一个按钮,点击该按钮就可以在其下面添加新的子项?
但是,在不同的论坛中查找后,我意识到在每个父项中设置按钮单击处理程序并不容易。但如果这是唯一的方法,是否有人可以给我一些示例代码?
我找到了这个线程,但无法将其实现到我的代码中。 Android Row becomes Unclickable with Button

你是如何填充列表的?使用游标吗?还是使用数组? - Barak
1个回答

6

给群组视图添加一个按钮不应该很难。

我认为下面的代码可以实现(虽然我没有使用数组支持 ExpandableListView 的项目进行测试)。

由于我不知道您的分组行布局是什么样子的,因此我将在此处编写一个示例供参考。

group_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/test"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
    <TextView
        android:id="@android:id/text1"
        android:layout_width="wrap_content"
        android:layout_height="35dp"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:gravity="center_vertical"
        android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <Button
        android:id="@+id/addbutton"
        android:layout_width="wrap_content"
        android:layout_height="35dp"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:text="Add"
        android:textSize="12dp" />
</LinearLayout>

然后在你的适配器中的getGroupView方法中:

public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { 
    if (convertView == null) {
        View convertView = View.inflate(getApplicationContext(), R.layout.group_layout, null);
        Button addButton = (Button)convertView.findViewById(R.id.addButton);

        addButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                // your code to add to the child list
            }
        });
    }        
    TextView textView = (TextView)convertView.findViewById(R.id.text1);
    textView.setText(getGroup(groupPosition).toString()); 
    return convertView; 
} 

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