【发布时间】:2017-12-19 19:32:35
【问题描述】:
我的理解是 LinearLayout 应该分配 slack (额外空间)和/或收缩(负额外空间) 根据其孩子的布局权重。 这似乎适用于我对松弛的预期,但不适用于收缩。
以下 android Activity 演示。 它显示 9 列(垂直线性布局),不同程度 的拥挤。 9 列中的每一列都有两个子项:
- 第一个子列是一个子列,由标记为“A”、“B”、“C”的 3 个单选按钮组成
- second child 是一个子列,由标记为“0”、“1”的 2 个单选按钮组成
每个子列的权重与单选按钮的数量成正比 在其中(3 或 2),子列中每个单选按钮的权重为 1。
我选择这些权重是为了分配列的额外空间 (负或正)在其孙子(单选按钮)中均等, 以便给定列中的所有 5 个单选按钮最终大小相同。
它似乎可以正常工作(右侧的红色列), 但不适用于收缩(左侧的蓝色列),如下所示 屏幕截图显示(启用开发人员选项“显示布局边界”)。 在最拥挤(最左边)的列中差异最为明显, 其中前 3 个单选按钮最终比它们的 2 个表亲小得多。
这是 LinearLayout 的预期行为吗? 或者它是线性布局中的一个错误?还是我的程序中的错误?
这是程序列表(Kotlin):
// app/src/main/java/com/example/donhatch/linearlayoutweightsquestionactivity/MainActivity.kt
// Simple activity to test LinearLayout's slack/shrinkage distribution behavior.
package com.example.donhatch.linearlayoutweightsquestionactivity
import android.graphics.Color
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.RadioGroup
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val c = applicationContext
val WC = LinearLayout.LayoutParams.WRAP_CONTENT
setContentView(object: LinearLayout(c) {init{
// A row of 9 columns, from crowded to uncrowded.
orientation = HORIZONTAL
val columnHeights = arrayOf(
200, 300, 400, 500, // crowded
WC, // just right (comes out 5*112 = 560)
600, 700, 800, 900 // uncrowded
)
for (columnHeight in columnHeights) {
addView(object: LinearLayout(c) {init{
// A column with two child columns (radio groups).
orientation = VERTICAL
setBackgroundColor(when {
columnHeight==WC -> Color.WHITE
columnHeight<560 -> Color.argb(255,224,224,255) // crowded: blue
else -> Color.argb(255,255,224,224) // uncrowded: red
})
addView(object: RadioGroup(c) {init{
// First child column: three radio buttons.
orientation = VERTICAL
for (i in 0 until 3) {
addView(object: RadioButton(c) {init{
text = 'A'.plus(i) + " " // "A", "B", ...
}}, LayoutParams(WC, WC, 1.0f))
}
}}, LayoutParams(WC, WC, 3.0f)) // weight=3 for 3 children
addView(object: RadioGroup(c) {init{
// Second child column: two radio buttons.
orientation = VERTICAL
for (i in 0 until 2) {
addView(object: RadioButton(c) {init{
text = '0'.plus(i) + " " // "0", "1", ...
}}, LayoutParams(WC, WC, 1.0f))
}
}}, LayoutParams(WC, WC, 2.0f)) // weight=2 for 2 children
}}, LayoutParams(WC, columnHeight))
} // for columnHeight
}}) // setContentView
} // onCreate
} // class MainActivity
【问题讨论】:
标签: android android-layout android-linearlayout