Android:尝试使用数据绑定(bind)设置 CardView 的布局权重

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

我正在尝试使用以下代码将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>

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

最佳答案

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

您可以像这样创建 BindingAdapter

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

按如下方式使用绑定(bind)适配器属性

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

关于Android:尝试使用数据绑定(bind)设置 CardView 的布局权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65758045/

相关文章:

android - 单击父 View 时调用 subview onClickListener

java - 在Table Layout中的TextViews的onClickListener中添加动态数据

android - 在 Android 应用程序中定义 Activity 的布局

Android 无法删除自定义标题栏周围的填充

java - KOTLIN/JAVA 从对象列表中删除对象的一些属性

android - 如何从协程 kotlin 获取值(value)?

java - 声明 Object 的新实例会导致 OutOfMemoryFailure。为什么?

java - 在 genymotion 上运行 libgdx 游戏?

android - 如何将箭头放在 ListView 的同一行中?

android - 如何在 mvvm 模式中登录成功时从 viewmodel 启动 Activity