【发布时间】:2020-04-25 21:24:56
【问题描述】:
我有这段 XML 代码,它可以按我的需要工作(LinearLayout 位于 ScrollView 的中心):
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@android:color/holo_red_dark"
android:layout_gravity="center">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="some text" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="some text" />
</LinearLayout>
</ScrollView>
但我需要 Java/Kotlin 中的这段代码,但是,我未能正确设置 android:layout_gravity,因为 LinearLayout 仍在顶部,而不是居中。
这是我的 Kotlin 代码:
ScrollView(context).also { scrollView ->
scrollView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
LinearLayout(context).also { linearLayout ->
linearLayout.orientation = LinearLayout.VERTICAL
linearLayout.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply {
gravity = Gravity.CENTER // have tried this
weight = 1f // and have tried this
}
linearLayout.gravity = Gravity.CENTER // have tried this
linearLayout.setBackgroundColor(0xff_00_ff_00.toInt())
IntRange(0, 2).forEach {
linearLayout.addView(TextView(context!!).apply {
text = "some text"
textSize = 50f
})
}
scrollView.addView(linearLayout)
}
}
我设法让它工作的唯一方法是将isFillViewport 设置为true 为ScrollView,但在这种情况下LinearLayout 占据了全部高度,这并不是我想要的。
将不胜感激任何帮助,建议
【问题讨论】:
标签: java android kotlin android-linearlayout android-scrollview