RecyclerView

》一直这么用RecyclerView都没总结过几次,大概说下RecyclerView这个东西吧

介绍:

1、RecyclerView.Adapter:负责托管数据集,为每一项Item创建布局并绑定数据。
2、RecyclerView.ItemDecoration,给Item添加分割线。需要继承该类自定义一个类。
3、RecyclerView.ItemAnimator负责处理Item增加或删除时的动画效果,系统提供了一个默认的动画类DefaultItemAnimator()。
4、RecyclerView.ViewHolder:负责承载Item视图的子布局。

先看看正常情况下的RecyclerView.Adapter

public class RecAdapterCommon extends RecyclerView.Adapter {
    private List data = new ArrayList<>();
    private Context context;

    public RecAdapterCommon(Context context) {
        this.context = context;
    }

    public void setData(List data) {
        if (data != null && data.size() > 0) {
            this.data.clear();
            this.data.addAll(data);
            notifyDataSetChanged();
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(context).inflate(R.layout.item_layout, parent, false);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Datas datas = data.get(position);
        if (datas != null) {
            holder.tv_name.setText(datas.getName());
            holder.tv_money.setText(datas.getMoney());
        }
    }

    @Override
    public int getItemCount() {
        return data.size();
    }
    

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView tv_name, tv_money;


        public MyViewHolder(View itemView) {
            super(itemView);
            tv_name = (TextView) itemView.findViewById(R.id.name_tv_item);
            tv_money = (TextView) itemView.findViewById(R.id.money_tv_item);
        }
    }
}
  • 以上RecyclerView.Adapter虽然是属于优化后的Adapter,可以很好应用,但是要是数据源List data改变为List person呢,(要是布局不同呢),又要去改Adapter,或者两个都有是不是也要添加一样的数据源不同的Adapter,所以,下来就要做到Adapter的同用,这样才完美

RecyclerView.Adapter的通用

1.数据怎么办?
可以将数据源改为泛型,传入什么数据就是什么数据,通用
2.布局怎么办?
同Context一样,在构造方法中实现,在外部传入
3.绑定怎么办?
将该RecyclerView.Adapter改为抽象类,实现对外的抽象方法

看代码:

public abstract class RecAdapterCommon extends RecyclerView.Adapter {
    private List data;
    private int mLayoutId;
    private Context context;

     public RecAdapterCommon(Context context,List data, int mLayoutId) {
        this.context = context;
        this.mLayoutId = mLayoutId;
        this.data = data;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //R.layout.item_layout===========>>> mLayoutId
        View v = LayoutInflater.from(context).inflate(mLayoutId, parent, false);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        T datas = data.get(position);
        if (datas != null) {
            convert(holder, datas);
        }
    }

    /**
     * 既然已接口的形式将数据要传出去,那么本类RecAdapterCommon也要改为接口形式添加abstract
     *
     * @param holder
     * @param datas
     */
    public abstract void convert(MyViewHolder holder, T datas);

    @Override
    public int getItemCount() {
        return data.size();
    }
}

通用ViewHolder
既然Adapter都通用了,那么ViewHolder也不可能独善其身了,那么我们可以将所有的控件都集中在一个泛型的View中就可以啦

public class MyViewHolder extends RecyclerView.ViewHolder {

    // 用来存放子View减少findViewById的次数
    private SparseArray mViews;

    public MyViewHolder(View itemView) {
        super(itemView);
        mViews = new SparseArray<>();
    }

    /**
     * 通过id获取view
     */
    public  T getView(int viewId) {
        // 先从缓存中找
        View view = mViews.get(viewId);
        if (view == null) {
            // 直接从ItemView中找
            view = itemView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    /**
     * 设置TextView文本
     */
    public MyViewHolder setText(int viewId, CharSequence text) {
        TextView tv = getView(viewId);
        tv.setText(text);
        return this;
    }
    
    /**
     * 设置ImageView的资源
     */
    public MyViewHolder setImageResource(int viewId, int resourceId) {
        ImageView imageView = getView(viewId);
        imageView.setImageResource(resourceId);
        return this;
    }
}

那么同用完了,要是我们的项目需求改了,客户现在要求有点击长按事件以及拖动和侧滑删除呢
1.点击长按事件都是很简单,对外实现接口就行
2.那么侧滑和拖动呢?正好SDK提供了ItemTouchHelper这样一个工具类帮助我们实现拖动和侧滑

  • 那么我们先创建CommonItemTouchHelper类继承ItemTouchHelper.Callback
public class CommonItemTouchHelper extends ItemTouchHelper.Callback {
    private static final float ALPHA_FULL = 1.0f;
    private CommonItemTouchHelperAdapter adapter;
    private boolean isLongPressDragEnabled = false, isItemViewSwipeEnabled = false;

    public CommonItemTouchHelper(CommonItemTouchHelperAdapter adapter) {
        this.adapter = adapter;
    }

    /**
     * 支持长按开始拖拽
     *
     * @return
     */

    public void setLongPressDragEnabled(boolean isLongPressDragEnabled) {
        this.isLongPressDragEnabled = isLongPressDragEnabled;
    }


    /**
     * 该方法返回true时,表示支持长按拖动,
     * 即长按ItemView后才可以拖动,我们遇到的场景一般也是这样的。默认是返回false。
     *
     * @return
     */
    @Override
    public boolean isLongPressDragEnabled() {
        return isLongPressDragEnabled;
    }

    /**
     * 支持左右滑动
     *
     * @return
     */
    public void setItemViewSwipeEnabled(boolean itemViewSwipeEnabled) {
        isItemViewSwipeEnabled = itemViewSwipeEnabled;
    }

    /**
     * 该方法返回true时,表示如果用户触摸并左右滑动了View,
     * 那么可以执行滑动删除操作,即可以调用到onSwiped()方法。默认是返回false。
     *
     * @return
     */
    @Override
    public boolean isItemViewSwipeEnabled() {
        return isItemViewSwipeEnabled;
    }

    /**
     * 持哪个方向的拖拽和滑动
     *
     * @param recyclerView
     * @param viewHolder
     * @return
     */
    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {

        if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
            int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.START | ItemTouchHelper.END;// 允许上下左右的拖动
            int swipeFlags = 0;//无触发
            return makeMovementFlags(dragFlags, swipeFlags);
        } else if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
            int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
            return makeMovementFlags(dragFlags, swipeFlags);
        }
        return 0;
    }

    /**
     * 从静止状态变为拖拽或者滑动的时候会回调该方法,参数actionState表示当前的状态。
     *
     * @param viewHolder
     * @param actionState
     */
    @Override
    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
        super.onSelectedChanged(viewHolder, actionState);
    }

    /**
     * 拖拽后调用
     *
     * @param recyclerView
     * @param viewHolder
     * @param target
     * @return
     */
    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        if (viewHolder.getItemViewType() != target.getItemViewType()) {
            return false;
        }
        adapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
        return false;
    }

    /**
     * 滑动删除后调用
     * 

* 当用户左右滑动Item达到删除条件时,会调用该方法, * 一般手指触摸滑动的距离达到RecyclerView宽度的一半时,再松开手指, * 此时该Item会继续向原先滑动方向滑过去并且调用onSwiped方法进行删除,否则会反向滑回原来的位置。 *

* 如果在onSwiped方法内我们没有进行任何操作,即不删除已经滑过去的Item, * 那么就会留下空白的地方,因为实际上该ItemView还占据着该位置,只是移出了我们的可视范围内罢了 * * @param viewHolder * @param direction */ @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { adapter.onItemDelete(viewHolder.getAdapterPosition()); } /** * 我们可以在这个方法内实现我们自定义的交互规则或者自定义的动画效果 * * @param c * @param recyclerView * @param viewHolder * @param dX * @param dY * @param actionState * @param isCurrentlyActive */ @Override public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE && dX > 200 || actionState == ItemTouchHelper.ACTION_STATE_SWIPE && dX < -200) {//滑动,手指没有离开屏幕 //左右滑动时改变Item的透明度 final float alpha = ALPHA_FULL - Math.abs(dX) / (float) viewHolder.itemView.getWidth(); viewHolder.itemView.setAlpha(alpha); viewHolder.itemView.setTranslationX(dX); } super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive); } /** * 当用户操作完毕某个item并且其动画也结束后会调用该方法, * 一般我们在该方法内恢复ItemView的初始状态,防止由于复用而产生的显示错乱问题。 * * @param recyclerView * @param viewHolder */ @Override public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { super.clearView(recyclerView, viewHolder); //重置改变,防止由于复用而导致的显示问题 viewHolder.itemView.setAlpha(ALPHA_FULL); } }

以上代码中的方法就不一一解释了,代码中都有注释,在代码中我们头一个private CommonItemTouchHelperAdapter接口类,主要是对外实现拖动和侧滑的方法,既然是对外的,那么我们的RecAdapterCommon就要实现它,来注意我们的item的改变

public abstract class RecAdapterCommon extends RecyclerView.Adapter implements CommonItemTouchHelperAdapter {
    
    //...部分代码略...

    public RecAdapterCommon(Context context,List data, int mLayoutId) {
        //...部分代码略...
        OnItemListener = (RecOnItemListener) context;
    }


    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
     
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //实现点击事件
                OnItemListener.onItemClickListener(v, position);
            }
        });
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                //实现长按事件
                OnItemListener.onItemLongClickListener(v, position);
                return false;
            }
        });
        //...部分代码略...
    }

    private RecOnItemListener OnItemListener;

    /**
     * 自定义对外实现点击、长按的接口
     */
    public interface RecOnItemListener {
        void onItemClickListener(View view, int position);

        void onItemLongClickListener(View view, int position);
    }

    /**
     * 拖动时
     *
     * @param formPosition
     * @param toPosition
     */
    @Override
    public void onItemMove(int formPosition, int toPosition) {
        //拖动交换位置
        Collections.swap(data, formPosition, toPosition);
        notifyItemMoved(formPosition, toPosition);
    }

    /**
     * 侧滑删除
     *
     * @param position
     */
    @Override
    public void onItemDelete(int position) {
        //侧滑删除
        data.remove(position);
        notifyItemRemoved(position);
    }
}

如果想监听点击和长按需要implements ``RecAdapterCommon.RecOnItemListener接口实现点击和长按的方法
想实现侧滑和拖动还需要再MainActivity中这样

        //设置布局
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        // 给每个item添加分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        // 设置item增加和移除的动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        adapter = new MyAdapter(this, datasList, R.layout.layout_itemssss);
        recyclerView.setAdapter(adapter);

        //侧滑和拖动要配置这些才卡一实现----
        //创建CommonItemTouchHelper
        CommonItemTouchHelper callback = new CommonItemTouchHelper(adapter);
        callback.setItemViewSwipeEnabled(true);//设置可以侧滑
        callback.setLongPressDragEnabled(true);//可以拖拽
        //用Callback构造ItemtouchHelper
        ItemTouchHelper itemTouchHelper= new ItemTouchHelper(callback);
        //调用ItemTouchHelper的attachToRecyclerView方法建立联系
        itemTouchHelper.attachToRecyclerView(recyclerView);
上面拖动和策划完了,下来项目有改需求了,客户想要的侧滑是,侧滑时先出来个删除按钮,然后再点击删除才会删除数据否则不删除,那么下来我们就自己手动实现侧滑出现删除
  • 首先我们自定义一个布局View -> CommonSlidingButtonView继承HorizontalScrollView,我这里给它侧滑时出现两个按钮
public class CommonSlidingButtonView extends HorizontalScrollView {
    private TextView mTextView_Delete;
    private TextView mTextView_Save;
    private int mScrollWidth;
    private IonSlidingButtonListener mIonSlidingButtonListener;
    private Boolean isOpen = false;
    private Boolean once = false;
    private boolean isAllowableSliding = true;//是否允许侧滑

    public CommonSlidingButtonView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        getAttrs(context, attrs);
    }

    public CommonSlidingButtonView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.setOverScrollMode(OVER_SCROLL_NEVER);
        getAttrs(context, attrs);
    }

    /**
     * 添加可在xml文件中直接设置是否允许策划
     * @param context
     * @param attrs
     */
    private void getAttrs(Context context, AttributeSet attrs) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CommonSlidingButtonView);
        isAllowableSliding = ta.getBoolean(R.styleable.CommonSlidingButtonView_isAllowableSliding, true);
        ta.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (!once) {
            mTextView_Delete = (TextView) findViewById(R.id.common_delete);
            mTextView_Save = (TextView) findViewById(R.id.common_save);
            once = true;
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (changed) {
            this.scrollTo(0, 0);
            //获取水平滚动条可以滑动的范围,即右侧按钮的宽度
            mScrollWidth = mTextView_Delete.getWidth() + mTextView_Save.getWidth();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (isAllowableSliding) {
            int action = ev.getAction();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                case MotionEvent.ACTION_MOVE:
                    mIonSlidingButtonListener.onDownOrMove(this);
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    changeScrollx();
                    return true;
                default:
                    break;
            }
            return super.onTouchEvent(ev);
        } else {
            return true;
        }

    }

    /**
     * 按滚动条被拖动距离判断关闭或打开菜单
     */
    public void changeScrollx() {
        if (getScrollX() >= (mScrollWidth / 2)) {
            this.smoothScrollTo(mScrollWidth, 0);
            isOpen = true;
            mIonSlidingButtonListener.onMenuIsOpen(this);
        } else {
            this.smoothScrollTo(0, 0);
            isOpen = false;
        }
    }

    /**
     * 打开菜单
     */
    public void openMenu() {
        if (isOpen) {
            return;
        }
        this.smoothScrollTo(mScrollWidth, 0);
        isOpen = true;
        mIonSlidingButtonListener.onMenuIsOpen(this);
    }

    /**
     * 关闭菜单
     */
    public void closeMenu() {
        if (!isOpen) {
            return;
        }
        this.smoothScrollTo(0, 0);
        isOpen = false;
    }

    public void setSlidingButtonListener(IonSlidingButtonListener listener) {
        mIonSlidingButtonListener = listener;
    }

    public interface IonSlidingButtonListener {
        void onMenuIsOpen(View view);

        void onDownOrMove(CommonSlidingButtonView commonSlidingButtonView);
    }
}
  • 好了,布局完了,我们就根据这个布局View自定义一个xml的item(看布局)


    
        
            

                

                
            
        

        

        
    

  • 布局完了就该看他的Adapter了,我们让CommonRecyclerAdapter同时也实现接口CommonSlidingButtonView.IonSlidingButtonListener,先看看关于CommonSlidingButtonView的方法
 /*********************  侧滑  *************************/
    private CommonSlidingButtonView mMenu = null;

    /**
     * 删除菜单打开信息接收
     *
     * @param view
     */
    @Override
    public void onMenuIsOpen(View view) {
        mMenu = (CommonSlidingButtonView) view;
    }

    /**
     * 滑动或者点击了Item监听
     *
     * @param commonSlidingButtonView
     */
    @Override
    public void onDownOrMove(CommonSlidingButtonView commonSlidingButtonView) {
        if (menuIsOpen()) {
            if (mMenu != commonSlidingButtonView) {
                closeMenu();
            }
        }
    }

    /**
     * 关闭菜单
     */
    public void closeMenu() {
        mMenu.closeMenu();
        mMenu = null;
    }

    /**
     * 判断是否有菜单打开
     */
    public Boolean menuIsOpen() {
        if (mMenu != null) {
            return true;
        }
        return false;
    }

    public void removeData(int position) {
        mData.remove(position);
        notifyItemRemoved(position);
    }

同样,和我们的点击和长按事件一样给他添加策划的对外接口监听

    private OnItemListener OnItemListener;

    public interface OnItemListener {
        void onItemClickListener(View view, int position);
        void onItemLongClickListener(View view, int position);
        //侧滑栏中的删除点击
        void onItemSlidingClickListener(View view, int position);
    }

下来就简单了,每一次在点击或长按之前先判断侧滑是否打开

              //判断是否有删除菜单打开
                if (menuIsOpen()) {
                    closeMenu();//关闭菜单
                } else {
                    OnItemListener.onItemLongClickListener(v, position);
                }

同样,在点击侧滑栏里面的删除或者其他键之后记得关闭侧滑栏

              if (menuIsOpen()) {
                    closeMenu();//关闭菜单
                }
  • 到这里了估计就有人说了,他现在还是不能跑,跑起来碰下就直接crash 了,那是因为我们的ViewHolder还没配啊,来下来一起看看ViewHolder,ViewHolder中要用到CommonSlidingButtonView.IonSlidingButtonListener,又不在同类,只能在RecAdapterCommon中给留条后路,如下
    private static CommonSlidingButtonView.IonSlidingButtonListener ionSlidingButtonListener;
    public static CommonSlidingButtonView.IonSlidingButtonListener getIonSlidingButtonListener() {
        return ionSlidingButtonListener;
    }

那么在ViewHolder中就简单啦

    public MyViewHolder(View itemView) {
        super(itemView);
        mViews = new SparseArray<>();
        ((CommonSlidingButtonView) itemView).setSlidingButtonListener((CommonSlidingButtonView.IonSlidingButtonListener) CommonRecyclerAdapter.getIonSlidingButtonListener());
    }

在这里又出现问提了,我的删除键是根据消息内容显示的,要是太长画不出来,太短不划就出来了,还有点击长按都没用了怎么搞。
记得我们在布局里面有个父布局RelativeLayout包含了所以有的子布局是吧,我们直接给他设置个手机屏幕宽,点击长按事件也可以通过父布局设置

    /*******ViewHolder 中*******/
    public ViewGroup viewGroup;//内容的边框大小
    public TextView commonDelete, commonSave;//删除、收藏。。。。
    public MyViewHolder(View itemView) {
        super(itemView);
        mViews = new SparseArray<>();
        commonDelete = itemView.findViewById(R.id.common_delete);
        commonSave = itemView.findViewById(R.id.common_save);
        viewGroup = itemView.findViewById(R.id.common_content);
        ((CommonSlidingButtonView) itemView).setSlidingButtonListener((CommonSlidingButtonView.IonSlidingButtonListener) CommonRecyclerAdapter.getIonSlidingButtonListener());
    }


/******RecAdapterCommon中-----onBindViewHolder方法******/
    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
        //点击
        holder.viewGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断是否有删除菜单打开
                if (menuIsOpen()) {
                    closeMenu();//关闭菜单
                } else {
                    //可解决item拖动后让他的位置点也随之改变
                    int adapterPosition = holder.getAdapterPosition();
                    OnItemListener.onItemClickListener(v, adapterPosition );
                }
            }
        });
        //长按
        holder.viewGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断是否有删除菜单打开
                if (menuIsOpen()) {
                    closeMenu();//关闭菜单
                } else {
                    OnItemListener.onItemLongClickListener(v,  holder.getAdapterPosition());
                }
            }
        });
        //删除
        holder.commonDelete.setText("删除");
        holder.commonDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OnItemListener.onItemSlidingClickListener(v,  holder.getAdapterPosition());
                if (menuIsOpen()) {
                    closeMenu();//关闭菜单
                }
            }
        });
        //其他
        holder.commonSave.setText("其他");
        holder.commonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //其他。。。如:置顶、删除。。。。
                if (menuIsOpen()) {
                    closeMenu();//关闭菜单
                }
            }
        });

        if (data.get(position) != null) {
            convert(holder, data.get(position));
        }
    }
  • 这个是我在运行时发现的一个问题,正常情况没遇见过不知道为什么突然会这样,不过还好改变方式就可以了,上面为什么不用postion而用int adapterPosition = holder.getAdapterPosition();呢?
    因为一个的值会随拖动改变,一个不会变,会造成删除时出现crash(比如:)
    • 一共加载了两个item(itemA 原位置postion = 0,itemB 原位置postion = 1),先拖动itemAitemB的位置,那么看postion的变化,可以打印看看
-- 拖动前 拖动后
holder.getAdapterPosition() 0 1
position 0 0

》注意点*

1.如果自定义的侧滑和SDK工具ItemTouchHelper实现的侧滑同时开启,则优先使用ItemTouchHelper实现的侧滑,所以想要应用自定义这个必须在MainActivity中设置callback.setItemViewSwipeEnabled(false);//设置不可以侧滑同时在CommonSlidingButtonView布局中添加上app:isAllowableSliding= true允许侧滑
2.RecyclerView设置时必须设置布局,不然不会显示

最终源码:

ViewHodler

public class CommonViewHodler extends RecyclerView.ViewHolder {
    // 用来存放子View减少findViewById的次数
    private SparseArray mViews;
    public ViewGroup viewGroup;//内容的边框大小
    public TextView commonDelete, commonSave;//删除、收藏。。。。

    public CommonViewHodler(View itemView) {
        super(itemView);
        mViews = new SparseArray<>();
        commonDelete = itemView.findViewById(R.id.common_delete);
        commonSave = itemView.findViewById(R.id.common_save);
        viewGroup = itemView.findViewById(R.id.common_content);
        ((CommonSlidingButtonView) itemView).setSlidingButtonListener((CommonSlidingButtonView.IonSlidingButtonListener) CommonRecyclerAdapter.getIonSlidingButtonListener());
    }

    /**
     * 通过id获取view
     */
    public  T getView(int viewId) {
        // 先从缓存中找
        View view = mViews.get(viewId);
        if (view == null) {
            // 直接从ItemView中找
            view = itemView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    /**
     * 设置TextView文本
     */
    public CommonViewHodler setText(int viewId, CharSequence text) {
        TextView tv = getView(viewId);
        tv.setText(text);
        return this;
    }

    /**
     * 设置ImageView的资源
     */
    public CommonViewHodler setImageResource(int viewId, int resourceId) {
        ImageView imageView = getView(viewId);
        imageView.setImageResource(resourceId);
        return this;
    }
}

RecyclerView.Adapter

public abstract class CommonRecyclerAdapter extends RecyclerView.Adapter
        implements CommonSlidingButtonView.IonSlidingButtonListener, CommonItemTouchHelperAdapter {
    private static CommonSlidingButtonView.IonSlidingButtonListener ionSlidingButtonListener;
    protected static Context mContext;
    protected LayoutInflater mInflater;
    //数据
    protected List mData;
    // 布局
    private int mLayoutId;

    public static CommonSlidingButtonView.IonSlidingButtonListener getIonSlidingButtonListener() {
        return ionSlidingButtonListener;
    }

    public CommonRecyclerAdapter(Context context, List data, int layoutId) {
        this.mContext = context;
        this.mInflater = LayoutInflater.from(mContext);
        this.mData = data;
        this.mLayoutId = layoutId;
        OnItemListener = (CommonRecyclerAdapter.OnItemListener) context;
        ionSlidingButtonListener = this;
    }


    @Override
    public CommonViewHodler onCreateViewHolder(ViewGroup parent, int viewType) {

        // 先inflate数据
        View itemView = mInflater.inflate(mLayoutId, parent, false);
        // 返回ViewHolder
        CommonViewHodler holder = new CommonViewHodler(itemView);
        return holder;
    }

    @Override
    public void onBindViewHolder(CommonViewHodler holder, int position) {
        //设置内容布局的宽为屏幕宽度
        holder.viewGroup.getLayoutParams().width = Utils.getScreenWidth(mContext);

        holder.viewGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断是否有删除菜单打开
                if (menuIsOpen()) {
                    closeMenu();//关闭菜单
                } else {
                    //这里这个postion需要通过  holder.getAdapterPosition()获取的,
                    //请勿用上面position,因为拖动后上面的position不会改变,删除时会崩溃
                    OnItemListener.onItemClickListener(v, holder.getAdapterPosition());
                }
            }
        });
        holder.viewGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断是否有删除菜单打开
                if (menuIsOpen()) {
                    closeMenu();//关闭菜单
                } else {
                    OnItemListener.onItemLongClickListener(v, holder.getAdapterPosition());
                }
            }
        });

        holder.commonDelete.setText("删除");
        holder.commonDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OnItemListener.onItemSlidingClickListener(v, holder.getAdapterPosition());
                if (menuIsOpen()) {
                    closeMenu();//关闭菜单
                }
            }
        });
        holder.commonSave.setText("置顶");
        holder.commonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (menuIsOpen()) {
                    closeMenu();//关闭菜单
                }
            }
        });

        // 绑定怎么办?回传出去
        convert(holder, mData.get(position));
    }


    /**
     * ItemTouchHelper实现 拖动交换位置
     * 实现接口---CommonItemTouchHelperAdapter
     *
     * @param formPosition
     * @param toPosition
     */
    @Override
    public void onItemMove(int formPosition, int toPosition) {
        if (formPosition < toPosition) {
            for (int i = formPosition; i < toPosition; i++) {
                Collections.swap(mData, i, i + 1);
            }
        } else {
            for (int i = formPosition; i > toPosition; i--) {
                Collections.swap(mData, i, i - 1);
            }
        }
        Collections.swap(mData, formPosition, toPosition);
        notifyItemMoved(formPosition, toPosition);
    }

    /**
     * ItemTouchHelper实现侧滑删除
     * 实现接口---CommonItemTouchHelperAdapter
     *
     * @param position
     */
    @Override
    public void onItemDelete(int position) {
        removeData(position);
    }

    /**
     * 利用抽象方法回传出去,每个不一样的Adapter去设置
     * 

* // * @param item 当前的数据 */ public abstract void convert(CommonViewHodler holder, T item); @Override public int getItemCount() { return mData.size(); } /*******************点击、长按、侧滑s栏里的删除*************************/ private OnItemListener OnItemListener; public interface OnItemListener { void onItemClickListener(View view, int position); void onItemLongClickListener(View view, int position); void onItemSlidingClickListener(View view, int position); } /********************* 侧滑 *************************/ private CommonSlidingButtonView mMenu = null; /** * 删除菜单打开信息接收 * * @param view */ @Override public void onMenuIsOpen(View view) { mMenu = (CommonSlidingButtonView) view; } /** * 滑动或者点击了Item监听 * * @param commonSlidingButtonView */ @Override public void onDownOrMove(CommonSlidingButtonView commonSlidingButtonView) { if (menuIsOpen()) { if (mMenu != commonSlidingButtonView) { closeMenu(); } } } /** * 关闭菜单 */ public void closeMenu() { mMenu.closeMenu(); mMenu = null; } /** * 判断是否有菜单打开 */ public Boolean menuIsOpen() { if (mMenu != null) { return true; } return false; } public void removeData(int position) { mData.remove(position); notifyItemRemoved(position); } }

有更好的方法请热情告知,有不对的地方请多多指教

你可能感兴趣的:(RecyclerView)