gpt4 book ai didi

java - Android:在Java/Kotlin中的ScrollView内部居中LinearLayout

转载 作者:行者123 更新时间:2023-12-02 13:30:52 25 4
gpt4 key购买 nike

我在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)
}
}

我设法使其工作的唯一方法是将 isFillViewporttrue设置为 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)
}
}

关于java - Android:在Java/Kotlin中的ScrollView内部居中LinearLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61432821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com