RecycleView添加item点击效果

RecycleView不像ListView有自带的item点击效果 所以需要自己手动添加

最直接的方式是在onBindViewHolder()方法中对item添加View.setOnClickedLisetener();

这样如果需要在点击的时候将当前点击的positon传到监听方法中的话,每次onBindViewHolder()方法都会new一个Listener这样需要产生多个对象,未免浪费

所以这里的思路是通过ViewHolder来纪录当前被点击条目的position

上代码

public abstract class BaseRecycleViewAdapter<T extends BaseRecycleViewAdapter.ViewHolder> extends RecyclerView.Adapter<T> {

    private OnItemClickListener mOnItemClickListener;


    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private int mPosition = -1; //由ViewHolder纪录当前item的position 设置默认值为-1

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView); //这里使用了ButterKnife来代替findViewById
            itemView.setOnClickListener(this);//给ViewHolder添加点击事件
        }


        public void setPosition(int i) {
            mPosition = i; //用于向viewHolder传入position
        }

        @Override
        public void onClick(View v) {
        //把点击事件交给OnItemClickListener 来处理
            if (mOnItemClickListener != null) {
                if (mPosition != -1) {
                    mOnItemClickListener.onItemClicked(v, mPosition);
                } else {
                //如果没有给ViewHolder设置position会导致=-1
                    Debug.e("ViewHolder's positon = -1");
                }
            }

        }
    }

    //设置监听
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }
//用于最终实现监听的接口
    public interface OnItemClickListener {

        void onItemClicked(View v, int postion);

    }

}

使用时:

  class MyAdapter extends BaseRecycleViewAdapter {



        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            setOnItemClickListener(new MonthAdapter.OnClickListener());
            MyAdapter .ViewHolder holder = new MyAdapter .ViewHolder(LayoutInflater.from(mActivity).inflate(R.layout.myadapter , viewGroup, false));

       ...

            return holder;
        }

        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int i) {
            viewHolder.setPosition(i); //一定要运行这个方法

             ...

        }

        @Override
        public int getItemCount() {

            return list.size();
        }

        class ViewHolder extends BaseRecycleViewAdapter.ViewHolder {
            @Bind(R.id.item)
            Button item;

            public ViewHolder(View itemView) {
                super(itemView);
            }
        }

        //实现的点击监听
        class OnClickListener implements BaseRecycleViewAdapter.OnItemClickListener {

            @Override
            public void onItemClicked(View v, int postion) {
        //实现监听内容
                }
            }
        }
    }

完成

你可能感兴趣的:(Android控件,Android,RecyclerVi)