所需要的实现的效果如如
这里我们在给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;