转载请注明出处:http://blog.csdn.net/binbinqq86/article/details/54090829
RecyclerView的出现让许多人眼前一亮,当然在整个开发者圈子里面也拥有很不错的口碑,相比ListView而言,它高度灵活的使用方式也让很多新手感到不知所措,虽然做Android开发也有些时间了,但也是最近才转到RecyclerView上,不用不知道,一用就发现它真的很强大,比如传统的ListView和GridView所有的功能和效果它都能轻松实现,而最新的嵌套滑动它也能够很完美的支持,复杂的瀑布流效果对它而言就是小菜一碟,还有各种炫酷的item动画,总之只要你能够想到的就没有它实现不了的。
本文主要对RecyclerView中的ItemDecoration进行一个详细的讲解,虽然网上也有很多类似的文章,但想要真正理解关于这个抽象类的使用,具体每个方法和参数的含义是什么,怎么去实现一个自己想要的divider的时候,却发现其实不是那么容易,仍然需要自己去进行实践和整理,于是我就把自己所研究和理解的东西做一个相关的记录,同时也分享给大家。
首先贴上官方的解释:
An ItemDecoration allows the application to add a special drawing and layout offset to specific item views from the adapter's data set. This can be useful for drawing dividers between items, highlights, visual grouping boundaries and more.
All ItemDecorations are drawn in the order they were added, before the item views (in onDraw() and after the items (in onDrawOver(Canvas, RecyclerView, RecyclerView.State).
大致意思就是ItemDecoration允许应用去添加一个特殊的图形,并且布局在item的偏移处,这样就可以在item之间显示分割线。所有的分割线都被按照添加的顺序去绘制,onDraw是绘制在item的后面,而onDrawOver则是绘制在最上层。
当然官方也提供了一个默认的子类——android.support.v7.widget.DividerItemDecoration
这个类很简单,下面是代码:
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v7.widget;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewCompat;
import android.view.View;
import android.widget.LinearLayout;
/**
* DividerItemDecoration is a {@link RecyclerView.ItemDecoration} that can be used as a divider
* between items of a {@link LinearLayoutManager}. It supports both {@link #HORIZONTAL} and
* {@link #VERTICAL} orientations.
*
* <pre>
* mDividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
* mLayoutManager.getOrientation());
* recyclerView.addItemDecoration(mDividerItemDecoration);
* </pre>
*/
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
public static final int HORIZONTAL = LinearLayout.HORIZONTAL;
public st