android软件开发之仿淘宝选择规格的实现

  在一些app开发项目中选择商品规格这个功能最容易遇到问题,想要实现需要的全部功能,但一直没有成功,所以就去找了个Demo,学习界面UI采用recyclerview,item里面渲染ViewGroup,根据数据源的数量,往ViewGroup里面添加Textview。这样就可以解决它的每个属性按钮宽高自适应。下面来详细分享一下源码:

/**

* 测量子view大小 根据子控件设置宽和高

*/

@Override

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

{

super.onMeasure(widthMeasureSpec, heightMeasureSpec);

// 获得它的父容器为它设置的测量模式和大小

int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);

int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);

int modeWidth = MeasureSpec.getMode(widthMeasureSpec);

int modeHeight = MeasureSpec.getMode(heightMeasureSpec);

// 如果是warp_content情况下,记录宽和高

int width = 0;

int height = 0;

/**

* 记录每一行的宽度,width不断取最大宽度

*/

int lineWidth = 0;

/**

* 每一行的高度,累加至height

*/

int lineHeight = 0;

int cCount = getChildCount();

// 遍历每个子元素

for (int i = 0; i < cCount; i++)

{

View child = getChildAt(i);

// 测量每一个child的宽和高

measureChild(child, widthMeasureSpec, heightMeasureSpec);

// 得到child的布局管理器

MarginLayoutParams lp = (MarginLayoutParams) child

.getLayoutParams();

// 当前子空间实际占据的宽度

int childWidth = child.getMeasuredWidth() + lp.leftMargin

+ lp.rightMargin;

// 当前子空间实际占据的高度

int childHeight = child.getMeasuredHeight() + lp.topMargin

+ lp.bottomMargin;

/**

* 如果加入当前child,则超出最大宽度,则的到目前最大宽度给width,类加height 然后开启新行

*/

if (lineWidth + childWidth > sizeWidth)

{

width = Math.max(lineWidth, childWidth);// 取最大的

lineWidth = childWidth; // 重新开启新行,开始记录

// 叠加当前高度,

height += lineHeight;

// 开启记录下一行的高度

lineHeight = childHeight;

} else

// 否则累加值lineWidth,lineHeight取最大高度

{

lineWidth += childWidth;

lineHeight = Math.max(lineHeight, childHeight);

}

// 如果是最后一个,则将当前记录的最大宽度和当前lineWidth做比较

if (i == cCount - 1)

{

width = Math.max(width, lineWidth);

height += lineHeight;

}

}

setMeasuredDimension((modeWidth == MeasureSpec.EXACTLY) ?sizeWidth

: width, (modeHeight == MeasureSpec.EXACTLY) ? sizeHeight

: height);

}

@Override

protected void onLayout(boolean changed, int l, int t, int r, int b)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值