如何使用Android数据绑定在XML中设置layout_weight?在dimens文件夹中,我们以dp / sp为单位提供值。
@BindingAdapter("android:layout_weight")
fun setLayoutWeight(view: View, weight: Float) {
val layoutParams = view.layoutParams as? LinearLayout.LayoutParams
layoutParams?.let {
it.weight = weight
view.layoutParams = it
}
}
只需将此方法添加到与xml相关的java文件中:
@BindingAdapter("android:layout_weight")
public static void setLayoutWeight(View view, int weight) {
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view.getLayoutParams();
layoutParams.weight = weight;
view.setLayoutParams(layoutParams);
}
使用与之前讨论过的android:layout_width
和android:layout_height
相同的技术:
如何在Android中使用数据绑定绑定layout_width和layout_height
您必须创建自己的BindingAdapter。
试试这个:
@BindingAdapter("layout_weight")
fun setLayoutWeight(view: View, weight: Float) {
view.layoutParams = TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT,
weight)
}