RecyclerView更全解析之 基本使用和分割线解析

1.概述


  昨天跟自己群里的人唠嗑的时候发现还有人在用Eclipse,我相信可能还是有很多人在用ListView,这里介绍一个已经出来的n年了的控件RecyclerView,实现ListView,GridView,瀑布流的效果。还可以轻松的实现一些复杂的功能,如QQ的拖动排序,侧滑删除等等。

  **视频讲解:**http://pan.baidu.com/s/1jHW1X10

  相关文章:      RecyclerView更全解析之 - 基本使用和分割线解析      RecyclerView更全解析之 - 打造通用的万能Adapter      RecyclerView更全解析之 - 为它优雅的添加头部和底部      RecyclerView更全解析之 - 打造通用的下拉刷新上拉加载      RecyclerView更全解析之 - 仿支付宝侧滑删除和拖动排序

     

2.概述


  最终我们肯定要用到项目中,因为我觉得所有写的东西都必须封装好下次开发可以直接用到项目中。但是首先得要熟悉该控件才行。可以选择去google官方了解RecyclerView,但要翻墙。

  据官方的介绍,该控件用于在有限的窗口中展示大量数据集,其实这样功能的控件我们并不陌生,例如:ListView、GridView。

那么有了ListView、GridView为什么还需要RecyclerView这样的控件呢?整体上看RecyclerView架构,提供了一种插拔式的体验,高度的解耦,异常的灵活,通过设置它提供的不同LayoutManager,ItemDecoration , ItemAnimator实现令人瞠目的效果。

1.你想要控制其显示的方式,请通过布局管理器LayoutManager,ListView–>GridView–>瀑布流 只需要一行代码; 2.你想要控制Item间的间隔(可绘制),请通过ItemDecoration(这个比较蛋疼) ; 3.你想要控制Item增删的动画,请通过ItemAnimator; 4.你想要控制点击、长按事件,请自己写(擦,这点尼玛)。   

3.基本使用


  首先我们需要添加RecyclerView的依赖包,在build.gradle中添加依赖:

compile 'com.android.support:recyclerview-v7:24.0.0'
复制代码

  和ListView一样通过设置Adapter()给他绑定数据源,但在这之前必须设置setLayoutManager()这个方法是用来设置显示效果的(这样我们就可以通过设置布局管理显示不同的效果:ListView、GridView、瀑布流等等)。   

	// 设置recyclerView的布局管理  
	// LinearLayoutManager -> ListView风格
	// GridLayoutManager -> GridView风格
	// StaggeredGridLayoutManager -> 瀑布流风格
    LinearLayoutManager linearLayoutManager = new 
          LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(linearLayoutManager);
复制代码

3.1 Adapter编写

  接下来我们先去后台服务器请求数据,然后我们来编写Adapter,我们直接使用Okhttp获取服务器数据,在这里就不多说了,我们主要看Adapter怎么写。在ListView和GridView中我们可以不用ViewHolder,反正没人打我,只是数据特别多可能会崩溃而已;但是在RecyclerView中就不一样了它强制我们使用ViewHolder:

/**
 * Created by Darren on 2016/12/27.
 * Email: 240336124@qq.com
 * Description: 热吧订阅列表的Adapter
 */
public class CategoryListAdapter extends RecyclerView.Adapter<CategoryListAdapter.ViewHolder> {

    private List<ChannelListResult.DataBean.CategoriesBean.CategoryListBean> mList;
    private Context mContext;
    private LayoutInflater mInflater;

    public CategoryListAdapter(Context context, List<ChannelListResult.DataBean.CategoriesBean.CategoryListBean> list) {
        this.mContext = context;
        this.mList = list;
        this.mInflater = LayoutInflater.from(mContext);
    }

    /**
     * 创建条目ViewHolder
     *
     * @param parent   RecyclerView
     * @param viewType view的类型可以用来显示多列表布局等等
     * @return
     */
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // 创建条目
        View itemView = mInflater.inflate(R.layout.channel_list_item, parent, false);
        // 创建ViewHolder
        ViewHolder viewHolder = new ViewHolder(itemView);
        return viewHolder;
    }

    /**
     * 绑定ViewHolder设置数据
     *
     * @param holder
     * @param position 当前位置
     */
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // 设置绑定数据
        ChannelListResult.DataBean.CategoriesBean.CategoryListBean item = mList.get(position);
        holder.nameTv.setText(item.getName());
        holder.channelTopicTv.setText(item.getIntro());
        String str = item.getSubscribe_count() + " 订阅 | " +
                "总帖数 <font color='#FF678D'>" + item.getTotal_updates() + "</font>";
        holder.channelUpdateInfo.setText(Html.fromHtml(str));
        // 是否是最新
        if (item.isIs_recommend()) {
            holder.recommendLabel.setVisibility(View.VISIBLE);
        } else {
            holder.recommendLabel.setVisibility(View.GONE);
        }
        // 加载图片
        Glide.with(mContext).load(item.getIcon_url()).centerCrop().into(holder.channelIconIv);
    }

    /**
     * 总共有多少条数据
     */
    @Override
    public int getItemCount() {
        return mList.size();
    }

    /**
     * RecyclerView的Adapter需要一个ViewHolder必须要extends RecyclerView.ViewHolder
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView nameTv;
        public TextView channelTopicTv;
        public TextView channelUpdateInfo;
        public View recommendLabel;
        public ImageView channelIconIv;

        public ViewHolder(View itemView) {
            super(itemView);
            // 在创建的时候利用传递过来的View去findViewById
            nameTv = (TextView) itemView.findViewById(R.id.channel_text);
            channelTopicTv = (TextView) itemView.findViewById(R.id.channel_topic);
            channelUpdateInfo = (TextView) itemView.findViewById(R.id.channel_update_info);
            recommendLabel = itemView.findViewById(R.id.recommend_label);
            channelIconIv = (ImageView) itemView.findViewById(R.id.channel_icon);
        }
    }
}

复制代码

  3.2 分隔线定制

  对于分隔线这个也比较蛋疼,你会发现RecyclerView并没有支持divider这样的属性。那么怎么办,你可以在创建item布局的时候直接写在布局中,当然了这种方式不够优雅,我们早就说了可以自由的去定制它。   既然比较麻烦那么我们可以去github上面下载一个:DividerItemDecoration来参考一下。我这里就直接来写一个效果,大家也可以找找别人的博客看看。   分割线我们利用RecyclerView的addItemDecoration(ItemDecoration fromHtml) 新建一个类来看看到底是什么:

/**
 * Created by Darren on 2016/12/27.
 * Email: 240336124@qq.com
 * Description: RecyclerView 分割线定制
 */
public class CategoryItemDecoration extends RecyclerView.ItemDecoration {
    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {

    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
		
    }
}
复制代码

有两个方法getItemOffsets()这里我一般指定偏移量就可以了,就是分割线占多少高度,或者说是画在什么位置,你总的给我留出位置来;onDraw()我们可以直接去绘制,绘制什么都可以因为有Canvas ,但一般都是绘制Drawable,这里不多说具体看视频吧。

/**
 * Created by Darren on 2016/12/27.
 * Email: 240336124@qq.com
 * Description: RecyclerView 分割线定制
 */
public class CategoryItemDecoration extends RecyclerView.ItemDecoration {
    private Paint mPaint;

    public CategoryItemDecoration(int color) {
        // 直接绘制颜色  只是用来测试
        mPaint = new Paint();
        mPaint.setColor(color);
        mPaint.setAntiAlias(true);
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int childCount = parent.getChildCount();
        // 获取需要绘制的区域
        Rect rect = new Rect();
        rect.left = parent.getPaddingLeft();
        rect.right = parent.getWidth() - parent.getPaddingRight();
        for (int i = 0; i < childCount; i++) {
            View childView = parent.getChildAt(i);
            rect.top = childView.getBottom();
            rect.bottom = rect.top + 20;
            // 直接利用Canvas去绘制一个矩形 在留出来的地方
            c.drawRect(rect, mPaint);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        // 在每个子View的下面留出20px来画分割线
        outRect.bottom += 20;
    }
}
复制代码

看一下效果

  这只是用来测试一下,并不是我们所需要的效果,只是说一下这两个方法都可以干什么就是你想怎么弄分割线就怎么弄。我们一般会使用Drawable去画,所以我们必须调整成我们最终的效果,代码其实基本一致。

/**
 * Created by Darren on 2016/12/27.
 * Email: 240336124@qq.com
 * Description: RecyclerView 分割线定制
 */
public class CategoryItemDecoration extends RecyclerView.ItemDecoration {
    private Drawable mDivider;

    public CategoryItemDecoration(Drawable divider) {
        // 利用Drawable绘制分割线
        mDivider = divider;
    }

    @Override
    public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
        int childCount = parent.getChildCount();
        // 计算需要绘制的区域
        Rect rect = new Rect();
        rect.left = parent.getPaddingLeft();
        rect.right = parent.getWidth() - parent.getPaddingRight();
        for (int i = 0; i < childCount; i++) {
            View childView = parent.getChildAt(i);
            rect.top = childView.getBottom();
            rect.bottom = rect.top + mDivider.getIntrinsicHeight();
            // 直接利用Canvas去绘制
            mDivider.draw(canvas);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        // 在每个子View的下面留出来画分割线
        outRect.bottom += mDivider.getIntrinsicHeight();
    }
}
复制代码

  接下来我们就可以在drawable,下面新建一个xxx.xml的分割线文件了   

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <size android:height="0.5dp"   />
    <solid android:color="@color/list_item_divider" />
</shape>
复制代码

  基本没什么效果因为分割线比较小0.5dp,仔细看还是看得出来的,最后声明一下因为整个项目涉及到一键更换皮肤,那么恭喜恭喜这样做并没什么卵用,我们还是得直接写在item布局中,而不是用代码设置分割线。

  3.3 RecyclerView分割线源码解析      估计很大一部分的哥们在开发的时候都是使用的第三方的分割线,基本上都类似,一般都是利用系统自带的一个属性 android.R.attrs.listDriver我们直接获取这个属性的Drawable去绘制,那么这里我们分析一下源码去了解一些RecyclerView到底是怎样添加分割线的。   一万一千多行代码我们就只挑关键的方法:measureChild(),onDraw() , soeasy()

	// 只挑关键代码 一万一千多行太多了
	/**
	* Measure a child view using standard measurement policy, taking the padding
	* of the parent RecyclerView and any added item decorations into account.
	*
	* <p>If the RecyclerView can be scrolled in either dimension the caller may
	* pass 0 as the widthUsed or heightUsed parameters as they will be irrelevant.</p>
	*
	* @param child Child view to measure
	* @param widthUsed Width in pixels currently consumed by other views, if relevant
	* @param heightUsed Height in pixels currently consumed by other views, if relevant
	*/
	public void measureChild(View child, int widthUsed, int heightUsed) {
        final LayoutParams lp = (LayoutParams) child.getLayoutParams();
        // 关键看这个方法 --> getItemDecorInsetsForChild
        final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
        widthUsed += insets.left + insets.right;
        heightUsed += insets.top + insets.bottom;
        // 考虑分割线返回的Rect
		final int widthSpec = getChildMeasureSpec(getWidth(), getWidthMode(),
			getPaddingLeft() + getPaddingRight() + widthUsed, lp.width,
			canScrollHorizontally());
		final int heightSpec = getChildMeasureSpec(getHeight(), getHeightMode(),
			getPaddingTop() + getPaddingBottom() + heightUsed, lp.height,
			canScrollVertically());
		if (shouldMeasureChild(child, widthSpec, heightSpec, lp)) {
			child.measure(widthSpec, heightSpec);
		}
    }

	/**
	*  获取分割线装饰的Rect
	**/
	Rect getItemDecorInsetsForChild(View child) {
        final LayoutParams lp = (LayoutParams) child.getLayoutParams();
        if (!lp.mInsetsDirty) {
            return lp.mDecorInsets;
        }

        if (mState.isPreLayout() && (lp.isItemChanged() || lp.isViewInvalid())) {
            // changed/invalid items should not be updated until they are rebound.
            return lp.mDecorInsets;
        }
        final Rect insets = lp.mDecorInsets;
        insets.set(0, 0, 0, 0);
        final int decorCount = mItemDecorations.size();
        for (int i = 0; i < decorCount; i++) {
            mTempRect.set(0, 0, 0, 0);
            // getItemOffsets()还是比较熟悉,获取分割线返回的占用位置
            mItemDecorations.get(i).getItemOffsets(mTempRect, child, this, mState);
            // 开始累加占用位置
            insets.left += mTempRect.left;
            insets.top += mTempRect.top;
            insets.right += mTempRect.right;
            insets.bottom += mTempRect.bottom;
        }
        lp.mInsetsDirty = false;
        // 返回分割线的Rect
        return insets;
    }

	// onDraw()方法异常简单,自己体会一下吧
	@Override
    public void onDraw(Canvas c) {
        super.onDraw(c);

        final int count = mItemDecorations.size();
        for (int i = 0; i < count; i++) {
		    // 回调出去直接在getItemOffsets留出分割线位置的基础上直接绘制
            mItemDecorations.get(i).onDraw(c, this, mState);
        }
    }
复制代码

  3.4 长按和点击事件      这个是第二坑,第一坑就是上面的,后面还会有第三坑,RecyclerView并没有方法可以setOnItemClickListener()。我们只能在Adapter里面去写接口了,但是想想我们会有很多Adapter的每个都单独的去写会不会很麻烦。这个不用担心后面我们会写万能的Adapter,后面也会去自定义RecyclerView,目前只能这么弄了,修改修改Adapter:   

/**
 * Created by Darren on 2016/12/27.
 * Email: 240336124@qq.com
 * Description: 热吧订阅列表的Adapter
 */
public class CategoryListAdapter extends RecyclerView.Adapter<CategoryListAdapter.ViewHolder> {

    // 省略之前的代码 ......

    /**
     * 绑定ViewHolder设置数据
     *
     * @param holder
     * @param position 当前位置
     */
    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        // 省略之前的代码 ......

        // 设置点击和长按事件
        if (mItemClickListener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mItemClickListener.onItemClick(position);
                }
            });
        }
        if (mLongClickListener != null) {
            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    return mLongClickListener.onLongClick(position);
                }
            });
        }
    }
	
	// 省略之前的代码 ......


    /***************
     * 给条目设置点击和长按事件
     *********************/
    public OnItemClickListener mItemClickListener;
    public OnLongClickListener mLongClickListener;

    public void setOnItemClickListener(OnItemClickListener itemClickListener) {
        this.mItemClickListener = itemClickListener;
    }

    public void setOnLongClickListener(OnLongClickListener longClickListener) {
        this.mLongClickListener = longClickListener;
    }

    public interface OnItemClickListener {
        public void onItemClick(int position);
    }

    public interface OnLongClickListener {
        public boolean onLongClick(int position);
    }
}

复制代码

  估计有些不想接触新事物的哥们会觉得,哪里好用。他们都说好我觉得也好用着用着就好了因为公司的人都在用我不用也没办法。下一期我们还是解析RecyclerView可能会要更好用一些.

附视频地址:http://pan.baidu.com/s/1jHW1X10

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值