您好,登錄后才能下訂單哦!
Android 中RecycleView實現item的點擊事件
RecycleView現在已經越來越受到大家的重視,因為他既可以代替listView還可以代替GridView,但是RecycleView本身不不像ListView那樣具有setOnItemClickListener,這個關于子item的點擊,但是我們往往會用到RecycleView并且希望他的自孩子可以被點擊,那么如何實現他的item的點擊事件呢?
首先我們在RecyclerView.ViewHolder中的實現:
public class GridViewHolder extends RecyclerView.ViewHolder implements OnClickListener{ //聲明MyItemClickListener private MyItemClickListener mListener; public GridViewHolder(View rootView,MyItemClickListener listener) { super(rootView); this.mListener = listener; rootView.setOnClickListener(this); } @Override public void onClick(View v) { //如果mListener不為空,就實現接口中的方法onItemClick其中getPosition()是得到被點擊位置的position if(mListener != null){ mListener.onItemClick(v,getPosition()); } } //聲明MyItemClickListener這個接口 public interface MyItemClickListener { public void onItemClick(View view,int postion); } }
最后在RecyclerViewAdapter中實現:
package com.ledon.activity.adapter; import Java.util.ArrayList; import java.util.List; import com.ledon.activity.adapter.GridViewHolder.MyItemClickListener; import com.ledon.ledongym.R; import com.lidroid.xutils.BitmapUtils; import Android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; public class RecyclerViewAdapter extends RecyclerView.Adapter<GridViewHolder> { private final List<String> labels; private LayoutInflater mLayoutInflater; private Context context; private MyItemClickListener mItemClickListener; public RecyclerViewAdapter(int count, Context context) { this.labels = new ArrayList<String>(count); mLayoutInflater = LayoutInflater.from(context); for (int i = 0; i < count; i++) { labels.add(String.valueOf(i)); } } @Override public int getItemCount() { return labels.size(); } @Override public void onBindViewHolder(GridViewHolder viewHolder, int position) { viewHolder.itemView.setTag(labels.get(position)); } @Override public GridViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = null; view = mLayoutInflater.inflate(R.layout.item_userinfo, parent, false); //通過構造函數將mItemClickListener GridViewHolder holder = new GridViewHolder(view, mItemClickListener); return holder; } /** * 設置Item點擊監聽 * * @param listener */ public void setOnItemClickListener(MyItemClickListener listener) { this.mItemClickListener = listener; } }
最后在activity中
//根據adapter來設置item的點擊事件 recyclerViewAdapter.setOnItemClickListener(new MyItemClickListener() { @Override public void onItemClick(View view, int postion) { } });
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。