中山精品网站建设策划个人网站搭建
onMeasure里如何重置只有1个子view一行满屏, 若有多个自适应一行
可以尝试在 onMeasure
方法中重写 measureChildWithMargins
或 measureChild
方法来实现这个需求。
对于只有一个字的 View,我们可以把它的宽度设为屏幕宽度,高度设为最大高度,这样这个 View 就会占满一整行。
而对于多个 View 自适应的情况,我们可以先测量每个 View 的宽度,并累加得到它们的总宽度。如果总宽度小于屏幕宽度,那么我们可以将 View 的宽度设为屏幕宽度除以 View 的个数,这样所有 View 的宽度都相同,就可以一行放下了。否则,我们可以默认按原有的宽度进行布局,让它们分成多行。
以下是示例代码:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {// 获取父容器的尺寸规格int widthSize = MeasureSpec.getSize(widthMeasureSpec);int heightSize = MeasureSpec.getSize(heightMeasureSpec);int childCount = getChildCount();if (childCount == 1) { // 只有一个 View 的情况View child = getChildAt(0);// 让 View 的宽度填满屏幕,高度取最大值int widthMeasureSpecForChild = Measu