Search code examples
androidandroid-layoutandroid-databindingbackwards-compatibility

How to data-bind views per API level?


The requirement is not to display a bio-metric login button < API level 26 , because it isn't supported and therefore can be hidden for certain. method .setVisibility(View.GONE) is not an option, because the data-binding should configure the view all by itself.


Solution

  • One has to import android.os.Build.VERSION and android.view.View, in order to have constants VERSION.SDK_INT and class View available in the generated data-binding classes:

    <?xml version="1.0" encoding="utf-8"?>
    <layout
        xmlns:android="http://schemas.android.com/apk/res/android">
    
        <data>
            <import type="android.os.Build.VERSION"/>
            <import type="android.view.View"/>
        </data>
    
        <!-- only visible on API >= 26 -->
        <androidx.appcompat.widget.AppCompatImageView
            android:visibility="@{VERSION.SDK_INT >= 26 ? View.VISIBLE : View.GONE}"
            android:id="@+id/button_biometric_authentication"
            android:src="@drawable/ic_fingerprint_white_36dp"
            android:layout_gravity="center_vertical|end"
            android:layout_height="match_parent"        
            android:layout_width="wrap_content"/>
    
    </layout>