學習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對應的分組信息
    }
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容