处理 ExpandableRecyclerView 组视图中的点击事件

Handling click events inside ExpandableRecyclerView group view

我正在使用 this 库来实现 ExpandableRecyclerView。群组视图如下所示:

<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/expandable_list_group_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Group Heading" />

    <ImageButton
        android:id="@+id/expandable_list_delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_delete_black_24dp"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

expanding/collapsing 的点击事件由库处理,我通过适配器中的方法向列表添加元素。库的编码方式,有具体的添加和删除项目的通知方法:

Please note that the traditional notifyDataSetChanged() of RecyclerView.Adapter does not work as intended. Instead Expandable RecyclerView provides a set of notify methods with the ability to inform the adapter of changes to the list of ParentListItems.

notifyParentItemInserted(int parentPosition), notifyParentItemRemoved(int parentPosition), notifyParentItemChanged(int parentPosition), notifyParentItemRangeInserted(int parentPositionStart, int itemCount)

我想使用 ImageButton 来处理从列表中删除给定组的操作。为此,我必须访问适配器方法 notifyParentItemRemoved。我是否应该处理组的 ViewHolder 中的点击,如下所示:

public class MyParentViewHolder extends ParentViewHolder {

    TextView groupTitle;
    ImageButton deleteButton;

    public MyParentViewHolder(View itemView) {
        super(itemView);
        groupTitle = (TextView) itemView.findViewById(R.id.expandable_list_group_title);
        deleteButton = (ImageButton) itemView.findViewById(R.id.expandable_list_delete);
        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                   ... // somehow delete
            }
        });
    }

public void bind(...) {
    ...
}

如果是,我会怎样

  1. 访问我要删除的列表项? ArrayList 在适配器 class.
  2. 导致列表更新?需要调用Adapter的notify方法。

我应该在 ViewHolder 中引用 Adapter 吗?以这种方式处理它感觉不对。如果没有,那么我如何处理可扩展组视图中的点击事件?

由于没有任何回应,我不得不尝试自己解决问题。我不知道这是否是最好的方法(可能不是),但似乎别无选择。

从 Adapter 中,我将对适配器对象的引用传递给 ViewHolder 构造函数。单击是在 ViewHolder 本身内处理的。调用适配器方法,进一步调用通知方法。这很好用。