GridAdapter
1 package com.example.firstapp.recyclerview; 2 3 import android.content.Context; 4 import android.view.LayoutInflater; 5 import android.view.View; 6 import android.view.ViewGroup; 7 import android.widget.TextView; 8 9 import androidx.annotation.NonNull; 10 import androidx.recyclerview.widget.RecyclerView; 11 12 import com.example.firstapp.R; 13 14 import java.util.List; 15 16 public class GridAdapter extends RecyclerView.Adapter<GridAdapter.LinearViewHolder> { 17 18 private Context mContext; 19 private OnItemClickListener mlistener; 20 private List<String> list; 21 22 public GridAdapter(Context context, OnItemClickListener listener){ 23 this.mContext=context; 24 this.mlistener=listener; 25 } 26 27 @NonNull 28 @Override 29 public GridAdapter.LinearViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { 30 //这个方法需要return一个ViewHolder 31 return new LinearViewHolder( LayoutInflater.from( mContext ).inflate( R.layout.layout_grid_recyclerview_item,parent,false ) ); 32 } 33 34 @Override 35 public void onBindViewHolder(@NonNull GridAdapter.LinearViewHolder holder, final int position) { 36 //可以通过holder来设置一些内容 37 holder.textView.setText( "Hello" ); 38 39 holder.itemView.setOnClickListener( new View.OnClickListener() { 40 @Override 41 public void onClick(View v) { 42 //Toast.makeText( mContext, "click..."+position, Toast.LENGTH_SHORT ).show(); 43 mlistener.onclick( position ); 44 } 45 } );//设置点击事件,但是我这个上面没有显示 46 } 47 48 @Override 49 //列表长度 50 public int getItemCount() { 51 return 300; 52 } 53 54 class LinearViewHolder extends RecyclerView.ViewHolder{ 55 56 private TextView textView; 57 58 59 public LinearViewHolder(View itemView){ 60 super(itemView); 61 textView=itemView.findViewById( R.id.tv_title ); 62 } 63 } 64 //写一个接口用来接收点击事件的值 65 public interface OnItemClickListener{ 66 void onclick(int pos); 67 } 68 }