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