LinearLayout用代码实现分行
很多时候我们的子view个数不确定时,我们需要通过Java代码将子view添加到父view视图中,如果我们期望横向排列,当超出屏幕宽度后自动换行展示,这样的需求怎么实现呢?
效果:
代码实现 :
LinearLayout linearLayout = new LinearLayout( this ); |
02 | linearLayout.setOrientation(LinearLayout.VERTICAL); |
03 | LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); |
04 | layoutParams.setMargins( 0 , 20 , 0 , 20 ); |
05 | linearLayout.setLayoutParams(layoutParams); |
07 | LinearLayout newlinearLayout = new LinearLayout( this ); |
08 | newlinearLayout.setLayoutParams( new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); |
09 | newlinearLayout.setOrientation(LinearLayout.HORIZONTAL); |
10 | newlinearLayout.setLayoutParams(layoutParams); |
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( 0 , 0 ); |
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(); |
27 | newlinearLayout.addView(skuButton); |
30 | linearLayout.addView(newlinearLayout); |
原理:
首先我们定义一个纵向的LinearLayout 对象,在定义一个横向的LinearLayout ,在for循环中不断向横向的LinearLayout 中加入子view,但是在加入前需要判断,如果累计的宽度大于屏幕的宽度后,需要将此横向LinearLayout 作为子元素加入纵向的LinearLayout ,然后重新new出一个横向的LinearLayout 将view加入其中并重置累计宽度大小,如果累计宽度还是小于屏幕宽度,则继续向横向LinearLayout 加入子view。