RecycleView之GridLayoutManager的ItemDecoration

最近项目中,有需求去写一个九宫格的菜单,因为之前有用RecycleView,知道去设置不同的setLayoutManager,就会呈现出不同的列表样式。列表样式出来,但是还要加分隔线啊,到这里,就需要去重写RecyclerView.ItemDecoration,可以定制各种各样的分割线。
下面是我们需求需要的分割线:

上面就是我们需要的分割线,我们需求需要的是第二种,list.size()%column!=0时,bottomline占满屏幕宽度。这里我顺便把不占满屏幕的bottomline也画出来了。

这里mColumn默认为3,大家可以根据需求,来随意设置你需要的mColumn的值

具体写法:

public class RecyclerGridDecoration extends RecyclerView.ItemDecoration {

    private int[] attrs = new int[]{
            android.R.attr.listDivider
    };
    private Drawable divider;
    private int mColumn;
    private Context mContext;
    private int mTotalCount;
    private boolean isAllScreen;

    public RecyclerGridDecoration(Context context, int column, int totalCount) {
        super();
        mContext = context;
        TypedArray typedArray = context.obtainStyledAttributes(attrs);
        divider = typedArray.getDrawable(0);
        mTotalCount = totalCount;
        mColumn = column;
    }

    //bottomLine是否占满屏幕
    public void isAllScreen(boolean isAllScreen) {
        this.isAllScreen = isAllScreen;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        drawLine(parent, c);
    }

    private void drawLine(RecyclerView parent, Canvas c) {
        Paint paint = new Paint();
        paint.setColor(mContext.getResources().getColor(R.color.colorAccent));
        //设置画笔的宽度,这里的宽度需要和getItemOffsets()方法中的
        //left、top、right、bottom值的关系处理好,否则显示的效果会不理想
        paint.setStrokeWidth(Px2DpUtil.dp2px(mContext, 0.5f));
        //获得RecyclerView中总条目数量
        int childCount = parent.getChildCount();
        mTotalCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            //假设如果有一个header,就需要if判断i==0的情况,不需要去画线。
            // 几个header就需要去处理几次,即continue几次
//            if (i == 0) {
//                //如果是第一个item,我们就不用画边框了
//                continue;
//            }
            //获取每个子View,画上边框
            View childView = parent.getChildAt(i);
            //先获得子View在屏幕上的位置和它自身的宽高,利用这些参数去画线
            float x = childView.getX();
            float y = childView.getY();
            float width = childView.getWidth();
            float height = childView.getHeight();

            if (i % mColumn == 0) {
                View view = parent.getChildAt(i);
                float x1 = view.getX();
                float y1 = view.getY();
                //top
                c.drawLine(x1, y1, ScreenUtil.getScreenWidth(), y1, paint);
            }

            if ((i + 1) % mColumn != 0) {
                //right
                c.drawLine(x + width, y, x + width, y + height, paint);
            }

            int remainder = mTotalCount % mColumn;
            int temp = mTotalCount - i;
            if (isAllScreen) {
                //不满足list.size()%column==0,bottomLine全屏
                if ((temp <= remainder) || (temp <= mColumn && remainder == 0)) {
                    //bottom
                    c.drawLine(x, y + height, ScreenUtil.getScreenWidth(), y + height, paint);
                    //right
                    c.drawLine(x + width, y, x + width, y + height + divider.getIntrinsicHeight() / 2, paint);
                }
            } else {//不满足list.size()%column==0,bottomLine不全屏
                if ((temp <= remainder) || (temp <= mColumn && remainder == 0)) {
                    //bottom
                    c.drawLine(x, y + height, x + width, y + height, paint);
                    //right
                    c.drawLine(x + width, y, x + width, y + height + divider.getIntrinsicHeight() / 2, paint);
                }
            }
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State
            state) {
        int left = 0;
        int top = 0;
        int right = 0;
        int bottom = 0;
        int position = parent.getChildLayoutPosition(view);
        int remainder = mTotalCount % mColumn;
        int temp = mTotalCount - position;
        //这里判断,是为了list.size()%column==0且是最后一列
        //或者最后一列有余数,在这两种情况下,才需要去画bottomLine
        if ((temp <= remainder) || (temp <= mColumn && remainder == 0)) {
            //设置bottom留的边框值,这样画的bottomLine才能看见
            bottom = divider.getIntrinsicHeight();
        }
        outRect.set(left, top, right, bottom);
    }
}

使用方式:

public class RecyclerViewGridManagerActivity extends AppCompatActivity {


    private int mColumn;
    private RecyclerView mRv;
    private RecyclerView mRv1;
    private RecyclerView mRv2;
    List<Image> lists = new ArrayList<>();
    List<Image> lists1 = new ArrayList<>();
    List<Image> lists2 = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view_grid_manager_layout);
        mRv = (RecyclerView) findViewById(R.id.id_rv);
        mRv1 = (RecyclerView) findViewById(R.id.id_rv1);
        mRv2 = (RecyclerView) findViewById(R.id.id_rv2);

        //list.size()
        int count = 6;
        for (int i = 0; i < count; i++) {
            Image image = new Image();
            image.setTitle("title" + i);
            image.setResId(R.drawable.ic_launcher);
            lists.add(image);
        }

        //列数
        mColumn = 3;
        noramlBottom();

        //修改list.size()
        count = 7;
        for (int i = 0; i < count; i++) {
            Image image = new Image();
            image.setTitle("title" + i);
            image.setResId(R.drawable.ic_launcher);
            lists1.add(image);
        }
        remainderNum();

        //再一次修改list.size()
        count = 8;
        for (int i = 0; i < count; i++) {
            Image image = new Image();
            image.setTitle("title" + i);
            image.setResId(R.drawable.ic_launcher);
            lists2.add(image);
        }
        remainderNum1();

    }

    //正常画bottomline
    private void noramlBottom() {
        final RecyclerGridDecoration2 lineService = new RecyclerGridDecoration2(this, mColumn, lists.size());
        GridLayoutManager managerService = new GridLayoutManager(this, mColumn);
        mRv.addItemDecoration(lineService);
        mRv.setLayoutManager(managerService);
        GridAdapter mGridAdapter = new GridAdapter(this);
        mGridAdapter.append(lists);
        mRv.setAdapter(mGridAdapter);
    }

    //有余数,bottomLine全屏
    private void remainderNum() {
        final RecyclerGridDecoration2 lineService = new RecyclerGridDecoration2(this, mColumn, lists1.size());
        lineService.isAllScreen(true);
        GridLayoutManager managerService = new GridLayoutManager(this, mColumn);
        mRv1.addItemDecoration(lineService);
        mRv1.setLayoutManager(managerService);
        GridAdapter mGridAdapter = new GridAdapter(this);
        mGridAdapter.append(lists1);
        mRv1.setAdapter(mGridAdapter);
    }

    //有余数,bottomLine不全屏
    private void remainderNum1() {
        final RecyclerGridDecoration2 lineService = new RecyclerGridDecoration2(this, mColumn, lists2.size());
        GridLayoutManager managerService = new GridLayoutManager(this, mColumn);
        mRv2.addItemDecoration(lineService);
        mRv2.setLayoutManager(managerService);
        GridAdapter mGridAdapter = new GridAdapter(this);
        mGridAdapter.append(lists2);
        mRv2.setAdapter(mGridAdapter);
    }

    //Model
    class Image {
        private String title;
        private int resId;

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public int getResId() {
            return resId;
        }

        public void setResId(int resId) {
            this.resId = resId;
        }
    }

    //Adapter
    class GridAdapter extends RecyclerView.Adapter<GridAdapter.GridHolder> {

        private Context mContext;
        private List<Image> lists;

        public GridAdapter(Context context) {
            mContext = context;
        }

        public void append(List<Image> list) {
            lists = list;
            notifyDataSetChanged();
        }

        @Override
        public GridAdapter.GridHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new GridHolder(LayoutInflater.from(mContext).inflate(R.layout.recycler_grid_item, parent, false));
        }

        @Override
        public void onBindViewHolder(GridAdapter.GridHolder holder, int position) {
            holder.ivIcon.setImageResource(lists.get(position).getResId());
            holder.tvTitle.setText(lists.get(position).getTitle());
        }

        @Override
        public int getItemCount() {
            return lists.size();
        }

        class GridHolder extends RecyclerView.ViewHolder {
            private ImageView ivIcon;
            private TextView tvTitle;

            public GridHolder(View itemView) {
                super(itemView);
                ivIcon = (ImageView) itemView.findViewById(R.id.iv_icon);
                tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
                GridLayoutManager.LayoutParams params = (GridLayoutManager.LayoutParams) itemView.getLayoutParams();
                params.width = LinearLayout.LayoutParams.MATCH_PARENT;
                params.height = ScreenUtil.getScreenWidth() / mColumn;
                itemView.setLayoutParams(params);
            }
        }
    }
}

activity.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="list.size()%column=0时,正常画"
            android:textColor="@color/black"
            android:textSize="20sp"/>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/id_rv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"/>


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="list.size()%column有余数时,bottomline 全屏"
            android:textColor="@color/black"
            android:textSize="20sp"/>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/id_rv1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="list.size()%column有余数时,bottomline 不全屏"
            android:textColor="@color/black"
            android:textSize="20sp"/>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/id_rv2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:layout_marginTop="20dp"/>

    </LinearLayout>

</ScrollView>

recycler_grid_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:clickable="true"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv_icon"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_gravity="center_horizontal"
        tools:background="#d71345"
        android:scaleType="centerCrop"/>

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_marginTop="10dp"
        tools:text="标题"
        />

</LinearLayout>

好了,自定义ItemDecoration到这里就全部结束了,感谢观看。

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

推荐阅读更多精彩内容