練習(xí)RecyclerView添加分割線

RecyclerView需要手動(dòng)添加分割線混狠,之前每次都是把代碼復(fù)制粘貼上去了。剛剛練習(xí)了一下如何添加豎線分割線和橫向間隔線以及雙向添加分割線。現(xiàn)在記錄一下减俏,但是繪制圖片部分需要修改,具體該怎么弄我要找一下資料歌溉。先放上普通單色線垄懂。




import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;

import static android.graphics.Paint.ANTI_ALIAS_FLAG;

/**
 * <pre>
 *  名稱:RecyclerViewItemDecoration
 *  作用:RecyclerView分割線
 *  描述:
 *  作者:pczhu
 *  創(chuàng)建時(shí)間: 2017/6/14 上午11:49
 *  版本:V1.0
 *  修改歷史:
 *  </pre>
 */

public class RecyclerViewItemDecoration extends RecyclerView.ItemDecoration {

    private Context mContext;
    /**
     * <pre>
     *      方向參數(shù)骑晶,默認(rèn)縱向
     *      0x10000000:Vertical縱向
     *      0x20000000:Horizontal橫向
     * </pre>
     */
    private int mOrientation = 0x10000000;
    /**
     * <pre>
     *      橫向
     * </pre>
     */
    public static final int Horizontal = 0x10000000;
    /**
     * <pre>
     *      縱向
     * </pre>
     */
    public static final int Vertical = 0x20000000;
    private Paint mPaint;
    /**
     * <pre>
     *      顏色參數(shù):分割線顏色
     *      默認(rèn)顏色:#eeeeee
     * </pre>
     */
    private int mDividerColor =  Color.parseColor("#000000");
    /**
     * <pre>
     *      分割線高度
     *          默認(rèn)2sp
     * </pre>
     */
    private int mDividerHeight = 2;
    /**
     * <pre>
     *     分割線寬度
     *          默認(rèn)2sp
     * </pre>
     */
    private int mDividerWidth = 2;
    private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
    private Drawable mDivider;

    private void setDividerColor(int mDividerColor) {
        this.mDividerColor = mDividerColor;
    }

    private void setDividerHeight(int mDividerHeight) {
        this.mDividerHeight = dip2px(mDividerHeight);
    }

    private void setDividerWidth(int mDividerWidth) {
        this.mDividerWidth = dip2px(mDividerWidth);
    }

    private void setDivider(Drawable mDivider) {
        this.mDivider = mDivider;
    }

    public void setOrientation(int mOrientation) {
        this.mOrientation = mOrientation;
    }

    /**
     * 默認(rèn)分割線:高度為2px,顏色為灰色
     *
     * @param context
     * @param orientation 列表方向
     */
    public RecyclerViewItemDecoration(Context context, int orientation) {
        this.mContext = context;
        if ((orientation & LinearLayoutManager.VERTICAL) == 1
                && (orientation & LinearLayoutManager.HORIZONTAL) == 1) {
            throw new IllegalArgumentException("請(qǐng)輸入正確的參數(shù)草慧!");
        }
        mOrientation = orientation;

        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
        if(mDivider==null){
            initPaint();
        }
    }


    /**
     * 初始化畫(huà)筆
     */
    private void initPaint() {
        mPaint = new Paint(ANTI_ALIAS_FLAG);
        mPaint.setColor(mDividerColor);
    }
    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        if(getLayoutManagerType(parent) != 2){

            if(mOrientation == (Horizontal|Vertical)){
                drawDividerBothLine(c,parent);
            }else if(mOrientation == Vertical){
                drawDividerVertical(c, parent);
            }else {
                drawDividerHorizontal(c,parent);
            }
        }

    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int spanCount = getSpanCount(parent);
        //特殊的item間距
        if(getLayoutManagerType(parent) == 2){//流 折半 每個(gè)偏移一半的值 相鄰就會(huì)偏移一個(gè)
            outRect.left = mDividerWidth/2;
            outRect.right = mDividerWidth/2;
            outRect.bottom = mDividerHeight/2;
            outRect.top = mDividerHeight/2;

        }else {//其他分割線
            if(mOrientation == (Horizontal|Vertical)){
                if((parent.getChildAdapterPosition(view)+1)%spanCount == 0){
                    outRect.set(0,0,0,mDividerHeight);
                }else {
                    outRect.set(0,0,mDividerWidth,mDividerHeight);
                }
            }else if(mOrientation == Vertical){
                outRect.set(0,0,0,mDividerHeight);
            }else if(mOrientation == Horizontal){
                outRect.set(0,0,mDividerHeight,0);
            }

        }
    }

    /**
     * 劃豎排列表的分割線
     * @param c
     * @param parent
     */
    private void drawDividerVertical(Canvas c,RecyclerView parent){
        int leftParent = parent.getPaddingLeft();
        int rightParent = parent.getWidth()-parent.getPaddingRight();

        int childCount = parent.getChildCount();
        for(int i = 0;i < childCount ; i++){
            View mChildView = parent.getChildAt(i);
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) mChildView.getLayoutParams();

            int left = leftParent+layoutParams.leftMargin;
            int right = rightParent-layoutParams.rightMargin;
            int top = mChildView.getBottom()+layoutParams.bottomMargin;
            if (mDivider != null) {
                mDivider.setBounds(left, top, right, top+mDividerHeight);
                mDivider.draw(c);
            }
            if (mPaint != null) {
//                Log.i("定點(diǎn)", left + ":" + top + ":" + right + ":" + (top + mDividerHeight));
                Rect rect = new Rect(left, top, right, (top + mDividerHeight));
                c.drawRect(rect, mPaint);
            }
        }
    }

    /**
     * 劃?rùn)M排列表間隔線
     * @param canvas
     * @param parent
     */
    private void drawDividerHorizontal(Canvas canvas, RecyclerView parent) {
        int top = parent.getPaddingTop();
        int bottom = parent.getMeasuredHeight() - parent.getPaddingBottom();
        int childSize = parent.getChildCount();
        for (int i = 0; i < childSize; i++) {
            View mChildView = parent.getChildAt(i);
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) mChildView.getLayoutParams();
            int left = mChildView.getRight() + layoutParams.rightMargin;
            int right = left + mDividerHeight;

            if (mDivider != null) {
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(canvas);

            }
            if (mPaint != null) {
                canvas.drawRect(left, top, right, bottom, mPaint);
            }
        }
    }

    /**
     * 同時(shí)畫(huà)橫向間隔線 豎向分割線
     * @param canvas
     * @param parent
     */
    private void drawDividerBothLine(Canvas canvas, RecyclerView parent) {
        int spanCount = getSpanCount(parent);
        int childSize = parent.getChildCount();
        for (int i = 0; i < childSize; i++) {
            View mChildView = parent.getChildAt(i);
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) mChildView.getLayoutParams();

            if((i+1) % spanCount == 0){//劃豎向行分界線

                int left = parent.getPaddingLeft()+layoutParams.leftMargin;
                int right = parent.getMeasuredWidth()-parent.getPaddingRight()-layoutParams.rightMargin;
                int top = mChildView.getBottom()+layoutParams.bottomMargin;
                int bottom = top+mDividerHeight;
                if (mDivider != null) {
                    mDivider.setBounds(left, top, right, bottom);
                    mDivider.draw(canvas);
                }
                if (mPaint != null) {
                    canvas.drawRect(left, top, right, bottom, mPaint);
                }
            }else{//劃?rùn)M向item間線

                int left = mChildView.getRight() + layoutParams.rightMargin;
                int right = left + mDividerWidth;
                int top = mChildView.getTop()-layoutParams.topMargin;
                int bottom = mChildView.getTop()+mChildView.getMeasuredHeight()+layoutParams.bottomMargin;
                if (mDivider != null) {
                    mDivider.setBounds(left, top, right, bottom);
                    mDivider.draw(canvas);
                }
                if (mPaint != null) {
                    canvas.drawRect(left, top, right, bottom, mPaint);
                }
            }
        }
    }
    /**
     * 獲取列數(shù)
     *
     * @param parent
     * @return
     */
    private int getSpanCount(RecyclerView parent) {
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        int spanCount = -1;
        switch (getLayoutManagerType(parent)){
            case 1:
                spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
                break;
            case 2:
                spanCount = ((StaggeredGridLayoutManager) layoutManager)
                        .getSpanCount();
                break;

        }
        return spanCount;
    }

    /**
     * 返回manager類型
     * @param parent
     * @return
     */
    private int getLayoutManagerType(RecyclerView parent){
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            return 1;
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            return 2;
        } else if (layoutManager instanceof LinearLayoutManager){
            return 3;
        }else{
            return -1;
        }
    }
    public static class Builder{
        private Context mContext;
        RecyclerViewItemDecoration recyclerViewItemDecoration;
        /**
         * <pre>
         *      方向參數(shù)桶蛔,默認(rèn)縱向
         *      0x10000000:Vertical縱向
         *      0x20000000:Horizontal橫向
         * </pre>
         */
        private int mOrientation = 0x10000000;
        /**
         * <pre>
         *      顏色參數(shù):分割線顏色
         *      默認(rèn)顏色:#eeeeee
         * </pre>
         */
        private int mDividerColor =  Color.parseColor("#000000");
        /**
         * <pre>
         *      分割線高度
         *          默認(rèn)2sp
         * </pre>
         */
        private int mDividerHeight = 2;
        /**
         * <pre>
         *     分割線寬度
         *          默認(rèn)2sp
         * </pre>
         */
        private int mDividerWidth = 2;
        /**
         * <pre>
         *     作為分割線的圖片資源
         * </pre>
         */
        private Drawable mDivider;

        public Builder(Context mContext) {
            this.mContext = mContext;
            recyclerViewItemDecoration = new RecyclerViewItemDecoration(mContext,mOrientation);
        }

        /**
         * 設(shè)置方向
         * @param mOrientation
         * @return
         */
        public Builder setOrientation(int mOrientation) {
            this.mOrientation = mOrientation;
            recyclerViewItemDecoration.setOrientation(mOrientation);
            return this;
        }

        /**
         * 設(shè)置顏色
         * @param mDividerColor
         * @return
         */
        public Builder setDividerColor(int mDividerColor) {
            this.mDividerColor = mDividerColor;
            recyclerViewItemDecoration.setDividerColor(mDividerColor);
            return this;
        }

        /**
         * 設(shè)置縱向分割線高度
         * @param mDividerHeight dp單位
         * @return
         */
        public Builder setDividerHeight(int mDividerHeight) {
            this.mDividerHeight = mDividerHeight;
            recyclerViewItemDecoration.setDividerHeight(mDividerHeight);
            return this;
        }

        /**
         * 設(shè)置分割線寬度
         * @param mDividerWidth dp單位
         * @return
         */
        public Builder setDividerWidth(int mDividerWidth) {
            this.mDividerWidth = mDividerWidth;
            recyclerViewItemDecoration.setDividerWidth(mDividerWidth);
            return this;
        }

        /**
         * 設(shè)置分割線圖片
         * @param mDivider
         * @return
         */
        public Builder setDivider(Drawable mDivider) {
            this.mDivider = mDivider;
            recyclerViewItemDecoration.setDivider(mDivider);
            return this;
        }
        public RecyclerViewItemDecoration build(){
            return recyclerViewItemDecoration;

        }
    }


    public int dip2px(float dpValue) {
        if(mContext == null){
            return 2;
        }
        final float scale = mContext.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根據(jù)手機(jī)的分辨率從 px(像素) 的單位 轉(zhuǎn)成為 dp
     */
    public int px2dip(float pxValue) {
        final float scale = mContext.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
}


        mRecyclerView.addItemDecoration(new RecyclerViewItemDecoration.Builder(this)
                .setOrientation(RecyclerViewItemDecoration.Vertical|RecyclerViewItemDecoration.Horizontal)
                .setDividerHeight(4)
                .setDividerWidth(4)
//                .setDivider(getResources().getDrawable(R.mipmap.abc))
                .setDividerColor(Color.parseColor("#eebbdd"))
                .build());
Markdown

Markdown
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市漫谷,隨后出現(xiàn)的幾起案子仔雷,更是在濱河造成了極大的恐慌,老刑警劉巖舔示,帶你破解...
    沈念sama閱讀 216,997評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件碟婆,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡惕稻,警方通過(guò)查閱死者的電腦和手機(jī)竖共,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)俺祠,“玉大人公给,你說(shuō)我怎么就攤上這事≈┰” “怎么了淌铐?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,359評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)蔫缸。 經(jīng)常有香客問(wèn)我腿准,道長(zhǎng),這世上最難降的妖魔是什么拾碌? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,309評(píng)論 1 292
  • 正文 為了忘掉前任吐葱,我火速辦了婚禮,結(jié)果婚禮上倦沧,老公的妹妹穿的比我還像新娘唇撬。我一直安慰自己,他們只是感情好展融,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,346評(píng)論 6 390
  • 文/花漫 我一把揭開(kāi)白布窖认。 她就那樣靜靜地躺著,像睡著了一般告希。 火紅的嫁衣襯著肌膚如雪扑浸。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,258評(píng)論 1 300
  • 那天燕偶,我揣著相機(jī)與錄音喝噪,去河邊找鬼。 笑死指么,一個(gè)胖子當(dāng)著我的面吹牛酝惧,可吹牛的內(nèi)容都是我干的榴鼎。 我是一名探鬼主播,決...
    沈念sama閱讀 40,122評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼晚唇,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼巫财!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起哩陕,我...
    開(kāi)封第一講書(shū)人閱讀 38,970評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤平项,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后悍及,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體闽瓢,經(jīng)...
    沈念sama閱讀 45,403評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,596評(píng)論 3 334
  • 正文 我和宋清朗相戀三年心赶,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了扣讼。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,769評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡园担,死狀恐怖届谈,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情弯汰,我是刑警寧澤,帶...
    沈念sama閱讀 35,464評(píng)論 5 344
  • 正文 年R本政府宣布湖雹,位于F島的核電站咏闪,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏摔吏。R本人自食惡果不足惜鸽嫂,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,075評(píng)論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望征讲。 院中可真熱鬧据某,春花似錦、人聲如沸诗箍。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,705評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)滤祖。三九已至筷狼,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間匠童,已是汗流浹背埂材。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,848評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留汤求,地道東北人俏险。 一個(gè)月前我還...
    沈念sama閱讀 47,831評(píng)論 2 370
  • 正文 我出身青樓严拒,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親竖独。 傳聞我的和親對(duì)象是個(gè)殘疾皇子裤唠,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,678評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容