Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android dataBinding - how to use bool resource to trigger visibility of layout

I currently have a bool.xml file in android which looks like this:

   <?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="showAds">true</bool>
    </resources>

Now i have a layout.xml file which uses databinding. I want to show or hide the visilibity of a adView based on a the boolean showAds defined above. So far i have this:

  <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
android:visibility="@{@bool/showAds ? View.Visible:View:gone}"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-1234567/34343">

but it does not compile. how can i get the boolean to decide if the ad should show or not ?The syntax is wrong.

like image 905
j2emanue Avatar asked Jan 16 '16 04:01

j2emanue


1 Answers

If you don't like adding the View import (in each layout where needed), you can simply define a @BindingConversion annotated method:

@BindingConversion
public static int convertBooleanToVisibility(boolean visible) {
    return visible ? View.VISIBLE : View.GONE;
}

The annotated method can be in whatever Java file in your project.

Then you can simply use

android:visibility="@{@bool/showAds}"
like image 196
Till Avatar answered Oct 31 '22 14:10

Till