学习recyclerview 中ItemDecoration记

定义:

Decoration 装饰物的意思,装饰Recyclerview的界面,常见的就是分割线。

简单的使用:

比如,简单的使用recyclerview,item布局中只有textview,加载进来之后没有分割线的,

如果想要好看点,加一条横向的分割线,可以在Adapter中的onCreateViewHolder方法中修改:

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
        RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) inflate.getLayoutParams();
        //开始设置为1,没有出现分割线的,以为没有效果,(进行设置分割线  好像没有效果)
        //有效果的,可以把值设置大一点
        params.topMargin = 100;
        inflate.setLayoutParams(params);
        return new ViewHolder(inflate);
    }

以上代码是在item布局文件中设置topMargin 或者bottomMargin
我们同样可以通过对Recyclerview添加ItemDecoration实现:
首先,创建MyTextItemDecoration
思路:通过recyclerview查看子view,如果是第一个,不需要画分割线,其他情况下的时候
getItemOffsets方法中outRect设置的偏移量左上右下全是0,我们重写只要top偏移有值,就会看到一条空白地带,实际上不是分割线(类似margin),但是看起来像是分割线。

public class MyTextItemDecoration extends RecyclerView.ItemDecoration {

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

//        //如果不是第一个,则设置top的值。
        if (parent.getChildAdapterPosition(view) != 0){
            //这个top的含义就是recyclerview内从第二个item开始,item与它上面的item之间的距离,可以对item设置背景色观察
            outRect.top = 1;
        }
    }
}

然后主需要调用Reacyclerview中的addItemDecoration()如下:

        mRecyclerView.setAdapter(new MyAdapter(mList));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        mRecyclerView.addItemDecoration(new MyTextItemDecoration());

但是,上面画的分割线效果与recyclerview背景色一样的,基本看不到的,如果要画别的颜色的分割线,就在
MyTextItemDecoration 类中onDraw方法中实现:

//如果需要绘制带有背景色的分割线可以在这里写逻辑
    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        mPaint = new Paint();
        mPaint.setColor(Color.BLUE);
        int count = parent.getChildCount();
        for (int i = 0; i < count; i++) {
            View view = parent.getChildAt(i);
            int position = parent.getChildAdapterPosition(view);
            if (position==0){
                continue;
            }
            float dividerTop = view.getTop()-mDiverderHeight;//(包含有分割线的高度)
            float dividerLeft = parent.getPaddingLeft();
            float dividerBottom = view.getTop();
            float dividerRight = parent.getWidth()-parent.getPaddingRight();
            c.drawRect(dividerLeft,dividerTop,dividerRight,dividerBottom,mPaint);
        }
    }

时间轴效果的代码:

public class TimeLineItemDecoration extends RecyclerView.ItemDecoration {

    private Paint mPaint;
    private float mOffestLeft;//item左边偏移量,为了显示时间轴结点
    private float mOffestTop;//item分割线高度
    //时间轴的结点半径
    private float mRaduis;
    private Context mContext;
    //如果时间节点用图标代替
    private Bitmap mIcon;

    public TimeLineItemDecoration(Context context) {
        mContext = context;
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.RED);

        mOffestLeft = context.getResources().getDimension(R.dimen.offest_left);
        mRaduis = context.getResources().getDimension(R.dimen.node_radius);

        mIcon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
        mIcon = Bitmap.createScaledBitmap(mIcon, (int) mRaduis * 2, (int) mRaduis * 2, false);
    }


    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        if (parent.getChildAdapterPosition(view) != 0) {
            mOffestTop = 1;
            outRect.top = 1;
        }

        outRect.left = (int) mOffestLeft;//设置左边的偏移量
    }


    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        int count = parent.getChildCount();
        for (int i = 0; i < count; i++) {
            View view = parent.getChildAt(i);
            int position = parent.getChildAdapterPosition(view);
            float itemHeight = view.getTop() - mOffestTop;//item上面的高度,如果是第一个的话为0 ,如果是非第一个,这个高度就会包括分割线的高度
            if (position == 0) {
                itemHeight = view.getTop();
            }

            float dividerLeft = parent.getPaddingLeft();
            float dividerBottom = view.getBottom();
            float dividerRight = parent.getWidth() - parent.getPaddingRight();

            float centerX = dividerLeft + mOffestLeft / 2;//recyclerview左边padding加上自己设置的左边偏移量的一半
            float centerY = itemHeight + (dividerBottom - itemHeight) / 2;//相当于一个item的高度,然后中心为每一个item高度的一半

            //计算结点上面的线坐标,
            float upLineTopX = centerX;
            float upLineTopY = itemHeight;
            float upLineBottomX = centerX;
            float upLineBottomY = centerY - mRaduis;


            c.drawLine(upLineTopX, upLineTopY, upLineBottomX, upLineBottomY, mPaint);//从上往下画

            //画圆点
//            c.drawCircle(centerX,centerY,mRaduis,mPaint);

            //画图标
            c.drawBitmap(mIcon, centerX - mRaduis, centerY - mRaduis, mPaint);


            float downLineTopX = centerX;
            float downLineTopY = centerY + mRaduis;
            float downLineBottomX = centerX;
            float downLineBottomY = dividerBottom;

            c.drawLine(downLineTopX, downLineTopY, downLineBottomX, downLineBottomY, mPaint);

        }
    }
}

热销书籍排行榜在onDrawover()方法中添加标签:


public class BookFlagItemDecoration extends RecyclerView.ItemDecoration {
    private Paint mPaint;
    private Bitmap mBitmap;
    private float mFlagLeft;
    private Context mContext;

    public BookFlagItemDecoration(Context context) {
        mContext = context;
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(Color.RED);
        mBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.hotsale);
        mFlagLeft = context.getResources().getDimension(R.dimen.offest_left);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        if (parent.getChildAdapterPosition(view) != 0) {
            outRect.top = 20;
        }
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDrawOver(c, parent, state);
        int count = parent.getChildCount();
        for (int i = 0; i < count; i++) {
            View view = parent.getChildAt(i);
            int position = parent.getChildAdapterPosition(view);

            float top = view.getTop();
            if (position < 3) {//前三画图标
                c.drawBitmap(mBitmap, mFlagLeft, top, mPaint);
            }
        }
    }
}

最重要的实现添加分组标签:
首先定义一个bean类管理标题

public class GroupInfo {
    private int groupID;//组号
    private String groupTitle;//标题
    private int position;//item在recyclerview中的位置


    public GroupInfo(int groupID, String groupTitle) {
        this.groupID = groupID;
        this.groupTitle = groupTitle;
    }

    //判断是否是组内第一个,因为只有组内第一个才会画title
    public boolean isFirstPosition() {
        return position == 0;
    }

    public void setPosition(int position) {
        this.position = position;
    }

    public String getGroupTitle() {

        return groupTitle;
    }

    public void setGroupTitle(String groupTitle) {
        this.groupTitle = groupTitle;
    }

    public int getGroupID() {

        return groupID;
    }

    public void setGroupID(int groupID) {
        this.groupID = groupID;
    }
}

然后写自己的itemdecoration

public class SectionItemDecoration extends RecyclerView.ItemDecoration {

    public GroupInfoCallback mCallback;
    private int mHeaderHeight;
    private int mDividerHeight;
    private Paint mPaint;
    private Context mContext;
    private int mTextoffest;
    private Paint.FontMetrics mFontMetrics;
    private Paint mTextPaint;
    private int mTextSize;

    public SectionItemDecoration(GroupInfoCallback callback, int dividerHeight, Context context) {
        mCallback = callback;
        mTextSize = 100;
        mHeaderHeight = 50;
        mHeaderHeight = (int) Math.max(mHeaderHeight, mTextSize);
        mDividerHeight = dividerHeight;
        mContext = context;

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.YELLOW);
        mFontMetrics = new Paint.FontMetrics();

        mTextPaint = new TextPaint();
        mTextPaint.setColor(Color.BLACK);
        mTextPaint.setTextSize(mTextSize);
        mFontMetrics = mTextPaint.getFontMetrics();

    }
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        //设置组与组之间的header高度,标题只需要绘制在分组的第一个itemview上面,数据需要标记,提供position,以及提供是否是第一个的方法
        int position = parent.getChildAdapterPosition(view);
        if (mCallback != null) {
            GroupInfo info = mCallback.getGroupInfo(position);
            if (info != null && info.isFirstPosition()) {
                outRect.top = mHeaderHeight;
            } else {
                outRect.top = mDividerHeight;
            }

        }
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        int count = parent.getChildCount();
        for (int i = 0; i < count; i++) {
            View view = parent.getChildAt(i);
            int position = parent.getChildAdapterPosition(view);
            if (mCallback != null) {
                GroupInfo info = mCallback.getGroupInfo(position);

                if (info != null && info.isFirstPosition()) {
                    int left = parent.getPaddingLeft();
                    //gettop为view自身的顶边距父布局顶边的距离
                    int top = view.getTop() - mHeaderHeight;
                    int right = parent.getWidth() - parent.getPaddingRight();
                    int bottom = view.getTop();
                    //绘制header
                    c.drawRect(left, top, right, bottom, mPaint);
                    float titleX = left + mTextoffest;
                    float titleY = bottom - mFontMetrics.descent;
                    c.drawText(info.getGroupTitle(), titleX, titleY, mTextPaint);

                }

            }

        }
    }

    //创建一个接口获取header的信息
    public interface GroupInfoCallback {
        GroupInfo getGroupInfo(int position);//获取每个itemview对应的分组信息
    }
}

在activity中使用的时候

public class GroupActivity extends AppCompatActivity implements SectionItemDecoration.GroupInfoCallback {
    private List<String> datas;
    private RecyclerView mRecyclerView;

    private MyAdapter mAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler);
        initData();
        mAdapter = new MyAdapter(datas);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mRecyclerView.setAdapter(mAdapter);

        SectionItemDecoration sectionItemDecoration = new SectionItemDecoration(this, 1, this);
        mRecyclerView.addItemDecoration(sectionItemDecoration);


    }

    private void initData() {
        datas = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            datas.add(i + "大神");
        }
    }

    @Override
    public GroupInfo getGroupInfo(int position) {
        //分组逻辑,5个一组
        int pos = position / 5;
        int index = position % 5;
        GroupInfo info = new GroupInfo(pos, pos + "");
        info.setPosition(index);
        return info;
    }
}

实现悬停的itemdecoration

public class StickySectionItemDecoration extends RecyclerView.ItemDecoration {
    public SectionItemDecoration.GroupInfoCallback mCallback;
    private int mHeaderHeight;
    private int mDividerHeight;
    private Paint mPaint;
    private Context mContext;
    private int mTextoffest;
    private Paint.FontMetrics mFontMetrics;
    private Paint mTextPaint;
    private int mTextSize;

    public StickySectionItemDecoration(SectionItemDecoration.GroupInfoCallback callback, int dividerHeight, Context context) {
        mCallback = callback;
        mTextSize = 100;
        mHeaderHeight = 50;
        mHeaderHeight = (int) Math.max(mHeaderHeight, mTextSize);
        mDividerHeight = dividerHeight;
        mContext = context;

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.YELLOW);
        mFontMetrics = new Paint.FontMetrics();

        mTextPaint = new TextPaint();
        mTextPaint.setColor(Color.BLACK);
        mTextPaint.setTextSize(mTextSize);
        mFontMetrics = mTextPaint.getFontMetrics();

    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        //设置组与组之间的header高度,标题只需要绘制在分组的第一个itemview上面,数据需要标记,提供position,以及提供是否是第一个的方法
        int position = parent.getChildAdapterPosition(view);
        if (mCallback != null) {
            GroupInfo info = mCallback.getGroupInfo(position);
            if (info != null && info.isFirstPosition()) {
                outRect.top = mHeaderHeight;
            } else {
                outRect.top = mDividerHeight;
            }

        }
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        int count = parent.getChildCount();
        for (int i = 0; i < count; i++) {
            View view = parent.getChildAt(i);
            int position = parent.getChildAdapterPosition(view);
            if (mCallback != null) {
                GroupInfo info = mCallback.getGroupInfo(position);

                if (info != null && info.isFirstPosition()) {
                    int left = parent.getPaddingLeft();
                    //gettop为view自身的顶边距父布局顶边的距离
                    int top = view.getTop() - mHeaderHeight;
                    int right = parent.getWidth() - parent.getPaddingRight();
                    int bottom = view.getTop();
                    //绘制header
                    c.drawRect(left, top, right, bottom, mPaint);
                    float titleX = left + mTextoffest;
                    float titleY = bottom - mFontMetrics.descent;
                    c.drawText(info.getGroupTitle(), titleX, titleY, mTextPaint);

                }

            }

        }
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int count = parent.getChildCount();
        for (int i = 0; i < count; i++) {
            View view = parent.getChildAt(i);
            int position = parent.getChildAdapterPosition(view);

            if (mCallback != null) {
                GroupInfo info = mCallback.getGroupInfo(position);
                int left = parent.getPaddingLeft();
                int right = parent.getWidth() - parent.getPaddingRight();

                //屏幕上第一个可见的itemview  i==0;
                if (i != 0) {
                    //组内第一个itemview才画title
                    if (info.isFirstPosition()) {
                        int top = view.getTop() - mHeaderHeight;
                        int bottom = view.getTop();
                        drawHeaderRect(c, info, left, top, right, bottom);
                    }
                } else {
                    //当item时屏幕上第一个可见的item时,不管是不是组内第一个 都要画header,才能实现悬停效果
                    int top = view.getPaddingTop();
                    int bottom = top + mHeaderHeight;
                    drawHeaderRect(c, info, left, top, right, bottom);

                }
            }
        }


    }


    private void drawHeaderRect(Canvas c, GroupInfo groupinfo, int left, int top, int right, int bottom) {
        //绘制Header
        c.drawRect(left, top, right, bottom, mPaint);

        float titleX = left + mTextoffest;
        float titleY = bottom - mFontMetrics.descent;
        //绘制Title
        c.drawText(groupinfo.getGroupTitle(), titleX, titleY, mTextPaint);
    }

    //创建一个接口获取header的信息
    public interface GroupInfoCallback {
        GroupInfo getGroupInfo(int position);//获取每个itemview对应的分组信息
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,189评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,577评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,857评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,703评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,705评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,620评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,995评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,656评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,898评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,639评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,720评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,395评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,982评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,953评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,195评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,907评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,472评论 2 342

推荐阅读更多精彩内容