这是关于我在代码审查中一直在争取的琐碎事情。情况就是这样。有一个数据绑定布局:some_layout.xml
,由ViewModel
支持。
[[some_layout.xml
的内容]
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<import type="android.view.View"/>
<variable name="viewModel" type="some.long.package.name.SomeViewModel"/>
</data>
<!-- Other stuffs -->
<TextView
<!-- Other parameters-->>
android:visibility="@{viewModel.someObservableBool?View.VISIBLE : View.GONE}"
/>
</layout>
要求,是这样,当布尔值为TextView
时,我希望View.GONE
为View.INVISIBLE
(而不是false
)。我的代码的审阅者坚持这一事实,对于android:visibility
[android:visibility="@{viewModel.someObservableBool}"
]
现在,我的理解是,由于将真值隐式转换为int,将导致视图为Visible
/ Invisible
而不是Gone
。正如attrs.xml
定义指出的那样。
<!-- Controls the initial visibility of the view. -->
<attr name="visibility">
<!-- Visible on screen; the default value. -->
<enum name="visible" value="0" />
<!-- Not displayed, but taken into account during layout (space is left for it). -->
<enum name="invisible" value="1" />
<!-- Completely hidden, as if the view had not been added. -->
<enum name="gone" value="2" />
</attr>
我的理解不正确吗?
Java中没有隐式类型转换,并且整数值不解释为布尔值-这意味着如果您编写
<TextView
<!-- Other parameters-->>
android:visibility="@{viewModel.someObservableBool}"
/>
它只会编译。
但是如果添加
@BindingConversion
fun booleanToVisibility(value: Boolean?) = if (value == true)View.VISIBLE else View.GONE
它应该工作。您可以查看相关文档here