如何在Kotlin代码中动态设置权重属性?

3

我该如何从Kotlin代码动态地为安卓中的LinerLayout设置layout_weight属性的值?

var orange : LinearLayout = findViewById(R.id.orangeLineFiveStars) as LinearLayout

这段代码是否正确?[它在我的应用程序中无法工作]

    var orangeParams : LinearLayout.LayoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)

    orangeParams.weight = 0.33f
    orange.layoutParams = orangeParams

这段代码也不起作用

var orange.layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT,0.33f)

XML :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.sanke.ilafedoseev.raitmyworkstatistic.MainActivity">

    <LinearLayout
        android:layout_margin="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/orangeLineFiveStars"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="4dp"
            android:background="#febe40"
            android:orientation="horizontal"/>

        <LinearLayout
            android:id="@+id/whiteLineFiveStars"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"/>

    </LinearLayout>
</LinearLayout>

可能是[以编程方式设置TextView的布局权重]的重复问题(https://dev59.com/9XA75IYBdhLWcg3wkZ6A)。 - Goku
它也不起作用。我为你的示例重写了代码,但没有任何改变。 - Илья Федосеев
尝试使用以下参数:var orangeParams: LinearLayout.LayoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 0.33f) - eugeneek
@eugeneek,它不起作用 :-( 什么都没有发生。 - Илья Федосеев
请将您的 XML 布局添加到问题中。 - eugeneek
@eugeneek,请在我的问题中添加XML。 - Илья Федосеев
2个回答

5

您需要记住,布局参数是从子视图传递到父视图的。您可能想要更改LinearLayout的某些子元素的layout_weight

在您的情况下,您可能想要像这样做:

(orangeLineFiveStars.layoutParams as LinearLayout.LayoutParams).weight = newOrangeWeight
(whiteLineFiveStars.layoutParams as LinearLayout.LayoutParams).weight = newWhiteWeight

可能还需要请求重新布局。

parentLinearLayout.requestLayout()

0
你可以尝试像这样做:
    yourView.layoutParams.apply {
         (this as LinearLayout.LayoutParams).weight = .33f //your value for weight

    }.requestLayout()

或者

val param = yourView.cardView.layoutParams as LinearLayout.LayoutParams
param.weight = .33f
yourView.layoutParams = param

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接