HorAdapter
package com.example.firstapp.recyclerview; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.firstapp.R; import java.util.List; public class HorAdapter extends RecyclerView.Adapter<HorAdapter.LinearViewHolder> { private Context mContext; private OnItemClickListener mlistener; private List<String> list; public HorAdapter(Context context, OnItemClickListener listener){ this.mContext=context; this.mlistener=listener; } @NonNull @Override public HorAdapter.LinearViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { //这个方法需要return一个ViewHolder return new LinearViewHolder( LayoutInflater.from( mContext ).inflate( R.layout.layout_hor_item,parent,false ) ); } @Override public void onBindViewHolder(@NonNull HorAdapter.LinearViewHolder holder, final int position) { //可以通过holder来设置一些内容 holder.textView.setText( "Hello" ); holder.itemView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { //Toast.makeText( mContext, "click..."+position, Toast.LENGTH_SHORT ).show(); mlistener.onclick( position ); } } );//设置点击事件,但是我这个上面没有显示 } @Override //列表长度 public int getItemCount() { return 30; } class LinearViewHolder extends RecyclerView.ViewHolder{ private TextView textView; public LinearViewHolder(View itemView){ super(itemView); textView=itemView.findViewById( R.id.tv_title ); } } //写一个接口用来接收点击事件的值 public interface OnItemClickListener{ void onclick(int pos); } }