androidandroid-layoutkotlindata-bindingandroid-layout-weight

Android: Trying to set layout weight for CardView using Databinding


I am trying to set the layout_weight to my CardView using below code:

<androidx.cardview.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:cardCornerRadius="8dp"
                app:cardBackgroundColor="@color/tile_bg_darkmode"
                android:layout_toLeftOf="@+id/tv_actual_score"
                android:layout_marginTop="@dimen/half_padding"
                android:background="@color/tile_bg_darkmode" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:weightSum="100"
                    android:orientation="horizontal">

                    <androidx.cardview.widget.CardView
                        android:id="@+id/cv_actual_progress"
                        android:layout_width="0dp"
                        android:layout_height="14dp"
                        app:cardCornerRadius="8dp"
                        app:cardBackgroundColor="@color/black"
                        android:layout_toLeftOf="@+id/tv_actual_score"
                        android:layout_weight="@{itemObj.actualtValue}"
                        android:background="@color/black" />

                </LinearLayout>



            </androidx.cardview.widget.CardView>

If I am trying with some constant value, it is showing the desired result but when i am trying with variable like above code, it is not working. actualValue is of float type as well. I tried many solutions but nothing seems working. Thanks in advance :)


Solution

  • Because that property does not support binding variable,

    You can create BindingAdapter like

    @BindingAdapter("variable_weight")
    fun setAdapter(view: View, weight: Float) {
      LinearLayout.LayoutParams params =    
      (view.getLayoutParams() as (LinearLayout.LayoutParams))
      params.weight = weight;
      view.setLayoutParams(params)
    }
    

    Use binding adapter property as follows

    <androidx.cardview.widget.CardView
                            android:id="@+id/cv_actual_progress"
                            android:layout_width="0dp"
                            android:layout_height="14dp"
                            app:cardCornerRadius="8dp"
                            app:cardBackgroundColor="@color/black"
                            android:layout_toLeftOf="@+id/tv_actual_score"
                            app:variable_weight="@{itemObj.actualtValue}"
                            android:background="@color/black" />