import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; public class aa extends RecyclerView.Adapter<aa.ViewHolder>{ private LayoutInflater mInflater; private ArrayList<String> data; private int choosePosition =-1; private OnRecyclerItemClickListener onRecyclerItemClickListener; public aa(Context context, ArrayList<String> data, int SavedSelectPosition, OnRecyclerItemClickListener RecyclerItemClickListener){ this.mInflater=LayoutInflater.from(context); this.data=data; this.choosePosition =SavedSelectPosition; this.onRecyclerItemClickListener=RecyclerItemClickListener; } /** * item显示类型 * @param parent * @param viewType * @return */ @NotNull @Override public ViewHolder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) { View view=mInflater.inflate(R.layout.music_rhythm_rv_item,parent,false); ViewHolder viewHolder=new ViewHolder(view); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { choosePosition = viewHolder.getAdapterPosition(); notifyDataSetChanged(); if(onRecyclerItemClickListener!=null){ onRecyclerItemClickListener.onItemClick(view, (int)view.getTag()); } } }); return viewHolder; } /** * 数据的绑定显示 * @param holder * @param position */ @Override public void onBindViewHolder(final ViewHolder holder, int position) { holder.tvChooseName.setText(data.get(position)); if (holder.getAdapterPosition() == choosePosition) { holder.ivChecked.setVisibility(View.VISIBLE); } else { holder.ivChecked.setVisibility(View.GONE); } holder.itemView.setTag(position); } @Override public int getItemCount() { //return mTitles.length; return data.size(); } public void setChoosePosition(int choosePosition) { this.choosePosition = choosePosition; } //自定义的ViewHolder,持有每个Item的的所有界面元素 public static class ViewHolder extends RecyclerView.ViewHolder { public TextView tvChooseName; public ImageView ivChecked; public ViewHolder(View view){ super(view); tvChooseName = view.findViewById(R.id.aaa); ivChecked =view.findViewById(R.id.bbb); } } /** * 自定义RecyclerView 中item view点击回调方法 */ public interface OnRecyclerItemClickListener{ /** * item view 回调方法 * @param view 被点击的view * @param position 点击索引 */ void onItemClick(View view, int position); } }
匿名内部类点击
不显示数据需要设置layoutmanager