标签:recyclerview onitemclick click
RecyclerView为了给开发者提供更大的自由度,没有默认的提供onItemClick接口。
网上有一种比较简单的实现方式 , 适用于不需要针对item里面某个按钮做特殊处理的情况
我目前项目的需求是,
1.单击item,跳转到用户信息页。
2.单击加关注按钮,更改按钮状态。
adapter代码如下
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.BaseViewHolder> { private List<User> mList; //用户列表 private Context mContext; public PraisedAdapter(Context context,List<User> list){ mContext = context; this.mList = list; } @Override public BaseViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View itemView = LayoutInflater.from(viewGroup.getContext()). inflate(R.layout.adapter_test, viewGroup, false); return new BaseViewHolder(itemView, new IMyViewHolderClicks() { @Override public void onItemClick(String uid) { // 跳转到个人信息页,根据uid获取个人信息 } //如果需要刷新某个特定界面,则参数中包含position @Override public void onFollowStatusChange(final User user,final int position) { //与服务器交互,如果成功,刷新当前按钮文字的 "关注"为"已关注" notifyItemChanged(position); } }); } @Override public void onBindViewHolder(final BaseViewHolder baseViewHolder,final int position) { User user = mList.get(position); baseViewHolder.bind(user); } @Override public int getItemCount() { return mList.size(); } public class BaseViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ TextView tvFollowStatus; //关注按钮 LinearLayout linearContainer; //整个item的根布局 IMyViewHolderClicks mListener; public BaseViewHolder(View v,IMyViewHolderClicks listener) { super(v); tvFollowStatus = (TextView)v.findViewById(R.id.tv_follow_status); linearContainer = (LinearLayout)v.findViewById(R.id.linear_container); mListener = listener; tvFollowStatus.setOnClickListener(this); linearContainer.setOnClickListener(this); } public void bind(User user) { if(user.getIs_attention()==1){ tvFollowStatus.setText("已关注"); }else{ tvFollowStatus.setText("加关注"); } //将实体绑定到view上面 tvFollowStatus.setTag(user); tvFollowStatus.setClickable(true); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.tv_follow_status: tvFollowStatus.setClickable(false); mListener.onFollowStatusChange((User) tvFollowStatus.getTag(),getLayoutPosition()); break; case R.id.linear_container: mListener.onItemClick(((User)tvFollowStatus.getTag()).getId()); break; } } } private interface IMyViewHolderClicks{ //单击整个item跳转到用户界面,需要传递uid public void onItemClick(String uid); //关注按钮,需要更新按钮的状态 public void onFollowStatusChange(User user,int position); } }
RecyclerView onItemClick 按钮和布局都有单击事件时的处理方式
标签:recyclerview onitemclick click
原文地址:http://blog.csdn.net/zglslyg/article/details/46401295