要实现 RecyclerView 不消费点击事件,由外层 LinearLayout 消费,可以通过以下步骤进行配置:

  1. 在布局文件中,将 RecyclerView 和外层 LinearLayout 放在同一个布局中,LinearLayout 作为外层布局。
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true"
    android:focusable="true"
    android:orientation="vertical">

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

</LinearLayout>
  1. 在 RecyclerView 的 Item 布局文件中,将根布局设置为可点击,但不可获取焦点。
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:focusable="false"
    android:orientation="horizontal">

    <!-- Item 内容 -->

</LinearLayout>
  1. 在 RecyclerView 的 Adapter 中,为 Item 布局的根布局设置点击事件监听器,并在监听器中处理点击事件。
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    // Adapter 相关代码

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_layout, parent, false);
        final ViewHolder viewHolder = new ViewHolder(itemView);
        
        // 设置点击事件监听器
        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理点击事件
            }
        });

        return viewHolder;
    }

    // ViewHolder 和其他方法的实现

}

这样配置后,RecyclerView 的 Item 布局的点击事件会被外层 LinearLayout 消费,而不会被 RecyclerView 消费。

Android RecyclerView 点击事件传递 - 外层 LinearLayout 消费

原文地址: https://www.cveoy.top/t/topic/ql8y 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录