Pro tip: More data binding — Easy view visibility in XML!

I heard you guys like data binding.  Here's another trick I've added to my portfolio: boolean visibility.

When I first started on Android, it seemed so obvious to me a View was visible, or not, I often made mistakes in my xml files like:


Don't laugh!  You know you do too.  After four years I can now type View.GONE in my sleep, so when I first started with data binding, I imported View and wrote code like this:
<import type="android.view.View"/>

android:visibility="@{user.role== null ? View.GONE : View.VISIBLE}"

You know this pattern; it exists wherever optional fields of data are displayed in the UI.  My code reviewer objected this was awkward and wordy.  I began to point out that View has three states of visibility and therefore a boolean would not do when I realized he was right.  I had some kind of View-induced Stockholm syndrome and there was now a better way — I had known it when I first started.

I now use 
app:visible="@{user.role!= null}"

and in my Java code, I wrote ONCE AND FOREVER:
public static void setVisible(View view, boolean visible) {
view.setVisibility(visible ? View.VISIBLE : View.GONE);


- Someone will probably ask; data binding does avoid NPEs (e.g. android:text="@{user.role}" would not throw an exception if role is null) but it will not automatically hide the view—just make it empty. Sometimes this is enough; often (like in the example user badge) you need to hide the view to achieve correct alignment or avoid gaps.
- What about View.INVISIBLE?!  You can still use it. If you want.

Data binding:
Shared publiclyView activity