前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >RecycleView之GridLayoutManager的ItemDecoration

RecycleView之GridLayoutManager的ItemDecoration

作者头像
code_horse
发布2018-07-02 14:26:29
3K0
发布2018-07-02 14:26:29
举报
文章被收录于专栏:Android NoteAndroid Note

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

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

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

具体写法:

代码语言:javascript
复制
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);
    }
}

使用方式:

代码语言:javascript
复制
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

代码语言:javascript
复制
<?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

代码语言:javascript
复制
<?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到这里就全部结束了,感谢观看。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.01.13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档