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

时间:2017-11-23 07:38:06

标签: android kotlin

如何从Kotlin代码动态设置android中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>

2 个答案:

答案 0 :(得分:2)

您需要记住布局参数从子视图传递到父视图。您可能想要更改LinearLayout的某个孩子的layout_weight

在你的情况下,你可能想做这样的事情

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

可能还需要请求重新布局

parentLinearLayout.requestLayout()

答案 1 :(得分: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