我有一个Android项目来创建可以单击的网格布局项目。我对在何处设置“单击监听器”以及代码的样子感到困惑。这是我的适配器代码程序:

public class MyAdapter extends RecyclerView.Adapter <FruitViewHolder> {

    private Context mContext;
    private List< FruitsData > mFruitList;

    MyAdapter(Context mContext, List< FruitsData > mFruitList) {
        this.mContext = mContext;
        this.mFruitList = mFruitList;
    }

    @Override
    public FruitViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_row, parent, false);
        return new FruitViewHolder(mView);

    }

    @Override
    public void onBindViewHolder(final FruitViewHolder holder, int position) {
        holder.mImage.setImageResource(mFruitList.get(position).getFruitImage());
        holder.mTitle.setText(mFruitList.get(position).getFruitName());


    }

    @Override
    public int getItemCount() {
        return mFruitList.size();
    }
}

class FruitViewHolder extends RecyclerView.ViewHolder {

    ImageView mImage;
    TextView mTitle;

    FruitViewHolder(View itemView) {
        super(itemView);

        mImage = itemView.findViewById(R.id.ivImage);
        mTitle = itemView.findViewById(R.id.tvTitle);


    }
}


感谢您的关注..

最佳答案

基本上,您必须执行以下步骤:


定义一个ClickListener接口

public interface OnItemClickListener {
  void onItemClick(FruitsData item);
}

将ClickListener传递给适配器的构造函数

MyAdapter(Context mContext, List<FruitsData > mFruitList, OnItemClickListener listener) {
    this.mContext = mContext;
    this.mFruitList = mFruitList;
    this.listener = listener;
 }

然后为侦听器创建一个setter

public void setListener(OnItemClickListener listener) {
  this.listener=listener;
}

//and ease your constructor

为您的viewHolder设置onClickListener并调用您的监听器

@Override
public void onBindViewHolder(final FruitViewHolder holder, int position) {
    final FruitsData item = mFruitList.get(position);
    holder.mImage.setImageResource(item .getFruitImage());
    holder.mTitle.setText(item getFruitName());
    holder.setOnClickListener(new View.OnClickListener() {
        @Override public void onClick(View v) {
            listener.onItemClick(item);
        }
    });
}

10-05 23:10