RecyclerView控件实现点击事件跟ListView控件不同,并没有提供类似setOnItemClickListener()这样的注册监听器方法,而是需要自己给子项具体的注册点击事件。
本文的例子是在上一篇文章的基础上修改的,上一篇文章:android中RecyclerView控件实现瀑布流布局
上一篇文章的代码,只需要修改NewsAdapter.java,注意红色部分内容是添加的内容:
package com.example.chenrui.app1; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.chenrui.common.News; import java.util.List; import java.util.Random; public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> { private List<News> newsList; public NewsAdapter(List<News> newsList) { this.newsList = newsList; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.news_item1,viewGroup,false); final ViewHolder viewHolder = new ViewHolder(view); viewHolder.newsImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = viewHolder.getAdapterPosition(); News news = newsList.get(position); Toast.makeText(v.getContext(), "新闻图片点击:你点击了新闻:" + news.getTitle(), Toast.LENGTH_SHORT).show(); } }); viewHolder.newsTitle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = viewHolder.getAdapterPosition(); News news = newsList.get(position); Toast.makeText(v.getContext(), "新闻标题点击:你点击了新闻:" + news.getTitle(), Toast.LENGTH_SHORT).show(); } }); return viewHolder; } @Override public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) { News news = newsList.get(i); viewHolder.newsImage.setImageResource(news.getPic()); ViewGroup.LayoutParams params = viewHolder.newsImage.getLayoutParams(); params.height = params.height + new Random().nextInt(300); viewHolder.newsImage.setLayoutParams(params); viewHolder.newsTitle.setText(news.getTitle()); } @Override public int getItemCount() { return newsList.size(); } static class ViewHolder extends RecyclerView.ViewHolder { ImageView newsImage; TextView newsTitle; public ViewHolder(@NonNull View itemView) { super(itemView); newsImage = itemView.findViewById(R.id.newsPic); newsTitle = itemView.findViewById(R.id.newsTitle); } } }
通过这个例子,点击新闻图片和新闻标题都会弹出对应的提示信息。