我在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
占据了整个高度,而这并不是我想要的。将不胜感激,忠告]
解决方案很简单,但是并不明显。我需要将LinearLayout.LayoutParams
更改为FrameLayout.LayoutParams
。所以Kotlin中的最终代码如下:
ScrollView(context).also { scrollView ->
scrollView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
LinearLayout(context).also { linearLayout ->
// I changed this line of code
linearLayout.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply {
gravity = Gravity.CENTER
}
linearLayout.orientation = LinearLayout.VERTICAL
linearLayout.setBackgroundColor(0xff_00_ff_00.toInt())
IntRange(0, 1).forEach {
linearLayout.addView(TextView(context!!).apply {
text = "some text"
textSize = 50f
})
}
scrollView.addView(linearLayout)
}
}