Android:RecyclerView中添加Item点击事件

Posted JMW1407

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android:RecyclerView中添加Item点击事件相关的知识,希望对你有一定的参考价值。


因为RecyclerView没有像ListView那样直接已经提供了OnItemClick或者OnItemLongClick等事件回调接口,所以需要自己来写一个。

方法1:直接在Adapter中的onCreateViewHolder方法中实现点击事件

RecyclerViewDemo

package com.example.activitytest;

import java.util.List;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class RecyclerViewDemo extends RecyclerView.Adapter<RecyclerViewDemo.MyViewHolder> {

  private List<String> list;
  private View inflater;

  public RecyclerViewDemo(List<String> list) {
    this.list = list;
  }


  @NonNull
  @Override
  public RecyclerViewDemo.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    inflater = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_demo,parent,false);
    MyViewHolder myViewHolder = new MyViewHolder(inflater);
    myViewHolder.mTextView.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        int position = myViewHolder.getAdapterPosition();
        Toast.makeText(v.getContext(),"点击了:"+ list.get(position),Toast.LENGTH_SHORT).show();
      }
    });
    return myViewHolder;
  }

  @Override
  public void onBindViewHolder(@NonNull RecyclerViewDemo.MyViewHolder holder, int position) {
    holder.mTextView.setText(list.get(position));
  }

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

  class MyViewHolder extends RecyclerView.ViewHolder{

    TextView mTextView;

    public MyViewHolder(@NonNull View itemView) {
      super(itemView);
      mTextView = (TextView)itemView.findViewById(R.id.text_view);
    }
  }
}

MainActivity

package com.example.activitytest;

import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {
  private final  String Tag = "====MainActivity:";

  private RecyclerView recyclerView;//声明RecyclerView
  private RecyclerViewDemo adapterDemo;//声明适配器
  private List<String> list;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(Tag,this.toString());
    setContentView(R.layout.activity_main);
    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    //添加数据
    list = new ArrayList<>();
    for (int i=0;i<50;i++){
      list.add("这是第"+i+"个测试");
    }

    adapterDemo = new RecyclerViewDemo(list);

    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(adapterDemo);
  }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  tools:context=".MainActivity">

  <androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</LinearLayout>

item_demo.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="50dp"
  android:orientation="vertical">

  <TextView
    android:id="@+id/text_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:text="测试"
    android:layout_margin="5dp"
    android:textColor="@android:color/holo_red_dark"
    android:background="@android:color/holo_blue_dark" />


</LinearLayout>

方法2:自定义接口,在activity或者fragment中调用

布局参考方法一:

具体步骤如下:

1、自定义一个接口:

package com.example.activitytest;

import java.util.List;

import android.view.View;

/**
 * 定义RecyclerView选项单击事件的回调接口
 */

public interface OnItemClickListener {
  //参数(父组件,当前单击的View,单击的View的位置,数据)
  public void onItemClick(View view, int position);

  // void onItemLongClick(View view);类似,我这里没用就不写了
  //
  //这个data是List中放的数据类型,如果这里是private List<Map> mapList;这样一个
  //然后我的每个item是这样的:
  //        HashMap map =new HashMap();
  //        map.put("img",R.drawable.delete);
  //        map.put("text","x1");
  //如果是item中只有text的话比如List<String>,那么data就改成String类型
}

2、在自定义的ViewHolder中实现onClickListenr接口,先声明一个自定义接口的变量,在自定义的ViewHolder的构造函数中添加一个参数-自定义的这个接口,并设置itemview的点击事件,在点击事件中转移到自定义的接口上,传到外面的调用者。
3、在自定义的Adapter中定义一个方法public void setOnItemClickListener(OnItemClickListener listener) {this.mClickListener = listener;}并暴露给外面的调用者

package com.example.activitytest;

import java.util.List;

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;

public class RecyclerViewDemo extends RecyclerView.Adapter<RecyclerViewDemo.MyViewHolder> {

  private List<String> list;
  private View inflater;

  private OnItemClickListener mClickListener;

  public RecyclerViewDemo(List<String> list) {
    this.list = list;
  }

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

  @NonNull
  @Override
  public RecyclerViewDemo.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    inflater = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_demo,parent,false);
    MyViewHolder myViewHolder = new MyViewHolder(inflater,mClickListener);
    /*myViewHolder.mTextView.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        int position = myViewHolder.getAdapterPosition();
        Toast.makeText(v.getContext(),"点击了:"+ list.get(position),Toast.LENGTH_SHORT).show();
      }
    });*/
    return myViewHolder;
  }

  @Override
  public void onBindViewHolder(@NonNull RecyclerViewDemo.MyViewHolder holder, int position) {
    holder.mTextView.setText(list.get(position));
  }

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


  class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    TextView mTextView;
    private OnItemClickListener mListener;// 声明自定义的接口

    public MyViewHolder(@NonNull View itemView, OnItemClickListener listener) {
      super(itemView);
      mListener = listener;
      // 为ItemView添加点击事件
      itemView.setOnClickListener(this);
      mTextView = (TextView)itemView.findViewById(R.id.text_view);
    }

    @Override
    public void onClick(View v) {
      // getpostion()为Viewholder自带的一个方法,用来获取RecyclerView当前的位置,将此作为参数,传出去
      mListener.onItemClick(v, getPosition());
    }
  }
}

4、在MainActivity中使用

package com.example.activitytest;

import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
  private final  String Tag = "====MainActivity:";

  private RecyclerView recyclerView;//声明RecyclerView
  private RecyclerViewDemo adapterDemo;//声明适配器
  private List<String> list;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(Tag,this.toString());
    setContentView(R.layout.activity_main);
    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    //添加数据
    list = new ArrayList<>();
    for (int i=0;i<50;i++){
      list.add("这是第"+i+"个测试");
    }

    adapterDemo = new RecyclerViewDemo(list);
    adapterDemo.setOnItemClickListener(new OnItemClickListener() {

      @Override
      public void onItemClick(View view, int position) {
        Toast.makeText(MainActivity.this, "点击了:" + position, Toast.LENGTH_SHORT).show();

      }
    });

    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(adapterDemo);
  }

}

方法3:修改RecyclerView源码,在里面实现点击事件

可参考:解决RecyclerView无法onItemClick问题

参考

1、https://blog.csdn.net/da_da_xiong/article/details/73256898
2、https://blog.csdn.net/RaphetS/article/details/51254538

以上是关于Android:RecyclerView中添加Item点击事件的主要内容,如果未能解决你的问题,请参考以下文章

Android:RecyclerView中添加Item点击事件

如何在Android Studio中添加RecyclerView-v7支持包

Android RecyclerView 添加和删除项

android recyclerview添加了一个数据怎么刷新

Firebase 通过多个查询搜索并添加到 RecyclerView Android Studio

如何在Android Studio中添加RecyclerView-v7支持包