1

我在我的项目中使用了可扩展的 recyclerview,数据来自 firebase 咨询。

我使用的可扩展 recyclerView 是:bignerdranch

更新我的观点的最佳方式是什么,因为该网站说:

请注意,传统notifyDataSetChanged()的 RecyclerView.Adapter 不能按预期工作

并推荐使用:

// 子变化

notifyChildInserted(int parentPosition, int childPosition)

...

但是,我不知道发生变化的 childPositions。

4

1 回答 1

0

由于循环,我对这个解决方案不是很自豪,但这是短名单的替代方案:

你可以从监听器获取点击的视图,从视图获取viewHolder,从视图持有者获取适配器位置,最后使用这些方法:

使用此方法

/**
 * Returns the adapter position of the Child associated with this ChildViewHolder
 *
 * @return The adapter position of the Child if it still exists in the adapter.
 * RecyclerView.NO_POSITION if item has been removed from the adapter,
 * RecyclerView.Adapter.notifyDataSetChanged() has been called after the last
 * layout pass or the ViewHolder has already been recycled.
 */
@UiThread
public int getChildAdapterPosition() {
    int flatPosition = getAdapterPosition();
    if (mExpandableAdapter == null || flatPosition == RecyclerView.NO_POSITION) {
        return RecyclerView.NO_POSITION;
    }

    return mExpandableAdapter.getChildPosition(flatPosition);
}

另见

/**
 * Given the index relative to the entire RecyclerView for a child item,
 * returns the child position within the child list of the parent.
 */
@UiThread
int getChildPosition(int flatPosition) {
    if (flatPosition == 0) {
        return 0;
    }

    int childCount = 0;
    for (int i = 0; i < flatPosition; i++) {
        ExpandableWrapper<P, C> listItem = mFlatItemList.get(i);
        if (listItem.isParent()) {
            childCount = 0;
        } else {
            childCount++;
        }
    }
    return childCount;
}

在这里定义侦听器的简单方法。

ItemClickSupport.addTo(mRecyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
    @Override
    public void onItemClicked(RecyclerView recyclerView, int position, View v) {
        // do it
    }
});

使用来获取 viewHolder:

@Override
public void onClick(View v) {
    MyHolder holder = (MyHolder) mRecyclerView.getChildViewHolder(v);
    holder.textView.setText("Clicked!");
}

检查视图类型了解单击的视图何时是父视图或子视图

  //Returns the view type of the item at position for the purposes of view recycling.
  @Override
  public int getItemViewType(int position) {
      if (items.get(position) instanceof User) {
          return USER;
      } else if (items.get(position) instanceof String) {
          return IMAGE;
      }
      return -1;
  }
于 2017-03-14T23:45:55.000 回答