android-layout - 如何使用 Android 数据绑定缩短条件表达式
问题描述
我只想使以下代码段更短且更具可读性。
<LinearLayout android:visibility="@{ viewModel.prediction.intent == PredictionIntentType.MEETING_FOLLOWUP || (viewModel.prediction.intent == PredictionIntentType.FOLLOWUP && !viewModel.isMeetingViewGroupShown) || (viewModel.prediction.intent == PredictionIntentType.MEETING && viewModel.isMeetingViewGroupShown) ? View.VISIBLE : View.GONE }" />
当我做多行(见下文)时,它不会编译
<LinearLayout
android:visibility="@{ viewModel.prediction.intent == PredictionIntentType.MEETING_FOLLOWUP
|| (viewModel.prediction.intent == PredictionIntentType.FOLLOWUP && !viewModel.isMeetingViewGroupShown)
|| (viewModel.prediction.intent == PredictionIntentType.MEETING && viewModel.isMeetingViewGroupShown)
? View.VISIBLE : View.GONE }" />
最终,我只希望它看起来像:
<LinearLayout android:visibility="@{ viewModel.someViewVisibility }" />
我正在使用Java
并且viewModel.prediction
是类型LiveData<Prediction>
,如果有帮助的话viewmodel.isMeetingViewGroupShown
是类型。LiveData<Boolean>
解决方案
最终,我只希望它看起来像:
<LinearLayout android:visibility="@{ viewModel.someViewVisibility }" />
所以就这样做:
视图模型:
val someViewVisibility: Int
@Bindable get() {
return if (prediction.intent == PredictionIntentType.MEETING_FOLLOWUP || (prediction.intent == PredictionIntentType.FOLLOWUP && !isMeetingViewGroupShown) || (prediction.intent == PredictionIntentType.MEETING && isMeetingViewGroupShown)) View.VISIBLE else View.GONE
}
使用视图模型中定义的属性,您的简化逻辑将起作用。另外,现在您可以编写单元测试someViewVisibility
并证明它有效。:)
希望有帮助!
推荐阅读
- selenium-webdriver - 尽管能够断言相同的元素,但无法找到元素
- python - 保持 Python 脚本运行的简单方法?
- c++ - 如何使用 OpenACC 实现用户自定义归约?
- ews-javascript-api - 如何使用 AutodiscoverUrl 方法?
- elasticsearch - 如何将段落与 ElasticSearch 中的短语匹配?
- python-3.x - 找到具有阈值的子列表之间最接近的值
- html - 如何让溢出在 CSS 网格中正常工作?
- node.js - 使用 systemctl 启动节点进程时如何加载 PATH 变量?
- ms-access - 控制查询字段的文本框
- c# - 有没有办法访问和更改以编程方式添加到面板的自定义控件中的值?