Android:在 Java / Kotlin 中将 LinearLayout 置于 ScrollView 内

Android: center LinearLayout inside ScrollView in Java / Kotlin

我在 XML 中有这段代码,它按我的要求工作(LinearLayoutScrollView 中居中):

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