Check Empty String In Android Data Binding

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}"
    >

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.