首页 > 解决方案 > Android XML 动态设置边距高度

问题描述

在 android 中,我需要让布局大小取决于 ViewModel 中的变量。例如:

<TextView
                android:id="@+id/amount"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Example"
                android:layout_marginTop="@{viewModel.interfaceEnable ? 0dp : 10dp}"
                />

根据 中的值viewModel.interfaceEnable,它要么是 0dp,要么是 10dp。但我得到的错误是:

Syntax error: extraneous input 'p' expecting {'.', '::', '[', '+', '-', '*', '/', '%', '<<', '>>>', '>>', '<=', '>=', '>', '<', 'instanceof', '==', '!=', '&', '^', '|', '&&', '||', '?', ':', '??'}

如何通过这种检查设置 dp 或任何值?

标签: androidandroid-layout

解决方案


你可以这样做:

android:layout_marginTop="@{viewModel.interfaceEnable ? @dimen/no_margin : @dimen/margin_normal}"

推荐阅读