让我困惑的是如何将视图绑定到Recycleler.ViewHolder.

public class RoomAdapter extends RecyclerView.Adapter<ViewHolder> {

  private OnItemClickListener mListener;
  private List<LocationBean> mRooms;

  static class ViewHolder extends RecyclerView.ViewHolder {

  @BindView(R.id.tv_title)
  TextView tvTitle;

  public ViewHolder(View itemView) {
   super(itemView);
   ButterKnife.bind(this, itemView);
   }
  }

  public void setData(List<LocationBean> rooms) {
   mRooms = rooms;
   notifyDataSetChanged();
  }

  @Override
  public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext())
      .inflate(R.layout.item_first_select, parent, false);
    return new ViewHolder(view);
  }

  @Override
  public void onBindViewHolder(final ViewHolder holder, int position) {
  holder.tvTitle.setText(mRooms.get(position).getLocation());

  holder.itemView.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
      mListener.onItemClickListener(v, holder.getLayoutPosition());
     }
    });
  }

  @Override
  public int getItemCount() {
    return mRooms == null ? 0 : mRooms.size();
  }

  public void setOnItemClickListener(OnItemClickListener listener) {
    mListener = listener;
  }

  public interface OnItemClickListener {
    void onItemClickListener(View v, int pos);
  }

}

推荐答案

posted solution行,但我想补充一点.viewholder模式的目的是只对每个视图进行一次昂贵的findViewById调用,然后将这些引用保存在ViewHolder中,并在需要绑定视图时从那里访问视图.

However, calling holder.itemView.tv_title.text in the onBindViewHolder method will cause a findViewById call to find the View that has the id tv_title within the itemView every time the viewholder is bound. This basically eliminates the performance gains and caching idea that viewholders are for.

您可以同时使用viewholder模式和Kotlin Android Extensions,方法是在ViewHolder中添加一个属性,并通过使用Extensions进行调用对其进行初始化,如下所示:

class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val title = itemView.tv_title
}

然后,您可以通过此属性访问View:

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.title.text = mRooms!!.get(position).getLocation()

    holder.itemView.setOnClickListener { v ->
        mListener?.onItemClickListener(v, holder.layoutPosition)
    }
}

最后,我建议取消!!运算符,改为执行NULL判断:

mRooms?.let { rooms ->
    holder.title.text = rooms[position].getLocation()
}

Kotlin相关问答推荐

在没有外部 map 的情况下转换列表项

为什么Kotlin函数参数名会 destruct 方法调用?

Kotlin:将泛型添加到列表任何>

如何在 kotlin 中的数据类中为变量提供多种类型

Kotlin .如何用从 1 到 90 的 5 个唯一数字填充列表中的每一行?

当 func 重载时,kotlin 如何确定调用哪个 func?

kotlin 如何决定 lambda 中的参数名称?

你怎么知道什么时候需要 yield()?

Kotlin:内部类如何访问在外部类中声明为参数的变量?

从 Java 调用 Kotlin 高阶函数

在粘贴时将 java 转换为 kotlin

是否可以在 kotlin 中嵌套数据类?

包括登录Elvis operator?

如何将vararg转换为list?

使用Dagger 2提供函数依赖性

从片段(fragment)中的点击事件启动协同程序

Android 上的 Kotlin:将map到list

Kotlin:具有多个不同类型设置器的单个属性

Kotlin out-projected 类型禁止使用

如何限制kotlin协程的最大并发性