【问题标题】:Android Data Binding : conditional formatting to set layout_weightAndroid 数据绑定:设置 layout_weight 的条件格式
【发布时间】:2017-07-05 08:39:38
【问题描述】:

如何使用android数据绑定在xml中设置layout_weight?在 dimens 文件夹中,我们提供 dp / sp 中的值。

【问题讨论】:

  • 为什么您的任务需要数据绑定?
  • 请向我们展示您到目前为止所做的尝试。

标签: android android-databinding


【解决方案1】:

这是一个适用于我的绑定适配器,您的视图确实需要在 LinearLayout 中,如果您想设置权重,我认为它会是:

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

【讨论】:

    【解决方案2】:

    只需将此方法添加到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);
    }
    

    【讨论】:

      【解决方案3】:

      使用与android:layout_widthandroid:layout_height 相同的技术,前面已经讨论过:

      How to bind a layout_width and layout_height using data binding in Android

      您必须创建自己的 BindingAdapter。

      【讨论】:

        【解决方案4】:

        试试这个:

        @BindingAdapter("layout_weight")
            fun setLayoutWeight(view: View, weight: Float) {
                view.layoutParams = TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,
                                                             TableLayout.LayoutParams.WRAP_CONTENT,
                                                             weight)
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-03-01
          • 2021-12-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多