3

How can I set the value for the attribute layout_weight for LinerLayout in android dynamically from Kotlin code ?

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

Is it right code ? [It doesn't work in my app]

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

    orangeParams.weight = 0.33f
    orange.layoutParams = orangeParams

This code doesn't work too

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 Answers2

5

You need to remember that layout parameters are passed from child to parent view. You probably want to change layout_weight of some child of LinearLayout.

In your case you probably want to do something like this

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

It may be necessary to also request re-layout

parentLinearLayout.requestLayout()
rafal
  • 3,120
  • 1
  • 17
  • 12
0

You cant try something like this:

    yourView.layoutParams.apply {
         (this as LinearLayout.LayoutParams).weight = .33f //your value for weight

    }.requestLayout()

Or

val param = yourView.cardView.layoutParams as LinearLayout.LayoutParams
param.weight = .33f
yourView.layoutParams = param
Vadym
  • 543
  • 5
  • 16