Check Empty String In Android Data Binding

March 11, 2018

The Data Binding expression below hide a layout if the string is empty.

<data>
    <import type="android.view.View"/>
    <variable name="viewModel" type="com.luasoftware.myapp.view.MainViewModel"/>
</data>

...

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:visibility='@{viewModel.username.equals("") ? View.GONE : View.VISIBLE}'
    >

NOTE: need to use outer single quote string in order to use double quote to represent empty string '@{viewModel.username.equals("") ? View.GONE : View.VISIBLE}'

NOTE: isNullOrEmpty (Kotlin) doesn’t work for Data Binding.

If you want to check for null and empty, it’s better to use TextUtils.isEmpty instead.

<data>
    <import type="android.view.View"/>
    <import type="android.text.TextUtils"/>
    <variable name="viewModel" type="com.luasoftware.myapp.view.MainViewModel"/>
</data>

...

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:visibility="@{TextUtils.isEmpty(viewModel.dataItem.username) ? View.GONE : View.VISIBLE}"
    >
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.