【问题标题】:expandable recyclerview update from firebase来自firebase的可扩展recyclerview更新
【发布时间】:2017-02-09 10:52:46
【问题描述】:

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

我使用的可展开recyclerView是:bignerdranch

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

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

并推荐使用:

// 子变化

notifyChildInserted(int parentPosition, int childPosition)

...

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

【问题讨论】:

  • 使用“点击侦听器”,您可以使用库方法获得视图、viewholder 和适配器位置。如果不是很长的列表,可以从第一个位置迭代到被点击的位置(parent ? count=0 : count++),count是循环后你的childposition。如果你检查他们的代码,你会发现他们做同样的事情。

标签: android firebase android-recyclerview expandablerecyclerview


【解决方案1】:

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

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

Use this method

/**
 * 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);
}

Also see

/**
 * 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;
}

定义监听器here的简单方法。

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

使用this获取viewHolder:

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

检查view typeknow when点击的视图是父还是子

  //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;
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    相关资源
    最近更新 更多