【问题标题】:Android: Trying to set layout weight for CardView using DatabindingAndroid:尝试使用数据绑定为 CardView 设置布局权重
【发布时间】:2021-01-17 06:49:18
【问题描述】:

我正在尝试使用以下代码将 layout_weight 设置为我的 CardView:

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

如果我尝试使用一些常量值,它会显示所需的结果,但是当我尝试使用上面代码之类的变量时,它不起作用。 actualValue 也是浮点类型。我尝试了很多解决方案,但似乎没有任何效果。在此先感谢:)

【问题讨论】:

    标签: android android-layout kotlin data-binding android-layout-weight


    【解决方案1】:

    因为该属性不支持绑定变量,

    你可以像这样创建 BindingAdapter

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

    如下使用绑定适配器属性

    <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" />
    

    【讨论】:

      猜你喜欢
      • 2021-03-11
      • 2020-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-26
      相关资源
      最近更新 更多