LinearLayout代码实现分行

LinearLayout用代码实现分行


很多时候我们的子view个数不确定时,我们需要通过Java代码将子view添加到父view视图中,如果我们期望横向排列,当超出屏幕宽度后自动换行展示,这样的需求怎么实现呢?

效果:


代码实现 :

LinearLayout linearLayout = new LinearLayout(this);
02                     linearLayout.setOrientation(LinearLayout.VERTICAL);
03                     LinearLayout.LayoutParams layoutParams = newLinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
04                     layoutParams.setMargins(020020);
05                     linearLayout.setLayoutParams(layoutParams);
06  
07                     LinearLayout newlinearLayout = new LinearLayout(this);
08                     newlinearLayout.setLayoutParams(newLinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
09                     newlinearLayout.setOrientation(LinearLayout.HORIZONTAL);
10                     newlinearLayout.setLayoutParams(layoutParams);
11  
12 for (Map.Entry skuEntry : skuProperty.getPropertyMap().entrySet()) {
13                         final Long skuId = (Long) skuEntry.getKey();
14                         final SkuPropertyValue propertyValue = (SkuPropertyValue) skuEntry.getValue();
15                         final String skuName = propertyValue.getName();
16                         final Button skuButton = new Button(this);
17                         skuButton.measure(00);
18                         widthSoFar += skuButton.getMeasuredWidth();
19                         if (widthSoFar >= maxWidth) {
20                             linearLayout.addView(newlinearLayout);
21                             newlinearLayout = new LinearLayout(this);
22                             newlinearLayout.setOrientation(LinearLayout.HORIZONTAL);
23                             newlinearLayout.setLayoutParams(layoutParams);
24                             newlinearLayout.addView(skuButton);
25                             widthSoFar = skuButton.getMeasuredWidth();
26                         else {
27                             newlinearLayout.addView(skuButton);
28                         }
29 }
30 linearLayout.addView(newlinearLayout);

原理:


首先我们定义一个纵向的LinearLayout 对象,在定义一个横向的LinearLayout ,在for循环中不断向横向的LinearLayout 中加入子view,但是在加入前需要判断,如果累计的宽度大于屏幕的宽度后,需要将此横向LinearLayout 作为子元素加入纵向的LinearLayout ,然后重新new出一个横向的LinearLayout 将view加入其中并重置累计宽度大小,如果累计宽度还是小于屏幕宽度,则继续向横向LinearLayout 加入子view。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值