首页 > 解决方案 > 如何使用 Android 数据绑定缩短条件表达式

问题描述

我只想使以下代码段更短且更具可读性。

<LinearLayout android:visibility="@{ viewModel.prediction.intent == PredictionIntentType.MEETING_FOLLOWUP || (viewModel.prediction.intent == PredictionIntentType.FOLLOWUP &amp;&amp; !viewModel.isMeetingViewGroupShown) || (viewModel.prediction.intent == PredictionIntentType.MEETING &amp;&amp; viewModel.isMeetingViewGroupShown) ? View.VISIBLE : View.GONE }" />

当我做多行(见下文)时,它不会编译

<LinearLayout 
  android:visibility="@{ viewModel.prediction.intent == PredictionIntentType.MEETING_FOLLOWUP 
    || (viewModel.prediction.intent == PredictionIntentType.FOLLOWUP &amp;&amp; !viewModel.isMeetingViewGroupShown) 
    || (viewModel.prediction.intent == PredictionIntentType.MEETING &amp;&amp; viewModel.isMeetingViewGroupShown) 
        ? View.VISIBLE : View.GONE }" />

最终,我只希望它看起来像:

<LinearLayout android:visibility="@{ viewModel.someViewVisibility }" />

我正在使用Java并且viewModel.prediction是类型LiveData<Prediction>,如果有帮助的话viewmodel.isMeetingViewGroupShown是类型。LiveData<Boolean>

标签: android-layoutandroid-databinding

解决方案


最终,我只希望它看起来像:

<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并证明它有效。:)

希望有帮助!


推荐阅读