RecycleView之GridLayoutManager的It

作者: Kotyo | 来源:发表于2018-01-13 10:16 被阅读617次

    最近项目中,有需求去写一个九宫格的菜单,因为之前有用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到这里就全部结束了,感谢观看。

    相关文章

      网友评论

        本文标题:RecycleView之GridLayoutManager的It

        本文链接:https://www.haomeiwen.com/subject/vimanxtx.html