利用RecyclerView实现九宫格,item的宽高一致(即为正方形)

所需要的实现的效果如如

image.png

这里我们在给RecyclerView LayoutManager时,给GridLayoutManager

mGridLayoutManager = new GridLayoutManager(this,8);

其中8是列数
在Adapter的ViewHolder中如下实现即可实现宽高相等

 FindWordHolder findWordHolder = new FindWordHolder(LayoutInflater.from(FindWordNormaPlayActivity.this).inflate(R.layout.item_find_word_text, viewGroup, false));
            ViewGroup.LayoutParams params = findWordHolder.itemView.getLayoutParams();
            ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) rvContent.getLayoutParams();
            //动态计算,设置item的宽高一致,总宽度-左右margin-左右padding /总列数-item左右margin-item左右padding
            params.height =
                    (mGridLayoutManager.getWidth() - layoutParams.leftMargin
                            - layoutParams.rightMargin - rvContent.getPaddingStart() - rvContent.getPaddingEnd()) / mGridLayoutManager.getSpanCount()
                            - 2 * findWordHolder.itemView.getPaddingLeft() - 2 * ((ViewGroup.MarginLayoutParams) params).leftMargin;
            return findWordHolder;

郑重声明,此文章仅作为自己学习笔记使用,如有侵权,请私信删除

你可能感兴趣的:(利用RecyclerView实现九宫格,item的宽高一致(即为正方形))