Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to import public static field from class in android data binding

I want to import some string from interface constant in android layout data binding.

Gradle build fails if i use this line

android:drawableRight="@{item.icon.equalsIgnoreCase(Constants.FOOD_TYPE_NON_VEG)? @drawable/ic_nonveg : @drawable/ic_veg}"

But below line works

android:drawableRight="@{item.icon.equalsIgnoreCase(`nonveg`)? @drawable/ic_nonveg : @drawable/ic_veg}"

Sample xml is

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <variable
            name="Constants"
            type="com.amelio.utils.Constants"/>

    </data>

    <TextView
        style="@style/tvVerySmall"
        android:layout_width="match_parent"
        android:drawableRight="@{item.icon.equalsIgnoreCase(`nonveg`)? @drawable/ic_nonveg : @drawable/ic_veg}"
        />

</layout>

and Constants interface is

public interface Constants {
    String FOOD_TYPE_NON_VEG  = "nonveg";
}

How to import string from interface in xml layout in databinding?

like image 296
Khemraj Sharma Avatar asked May 09 '18 10:05

Khemraj Sharma


People also ask

What is data binding in Android Studio?

Android data binding generates a Binding class based on this layout. This class holds all the bindings from the layout properties, i.e., the defined variable to the corresponding views. It also provides generated setters for your data elements from the layout.

What is the use of user variable in android Data Binding?

The user variable within data describes a property that may be used within this layout. Android data binding generates a Binding class based on this layout. This class holds all the bindings from the layout properties, i.e., the defined variable to the corresponding views. It also provides generated setters for your data elements from the layout.

How do I bind data to an Android event?

To enable the usage of data binding in your Android application, add the following snippet to the app/build.gradle file. 1.3. Data binding for events via listener bindings and method references Events may be bound to handler methods directly, similar to the way android:onClick can be assigned to a method in the activity.

How to write declarative layouts in Android using data binding?

Android offers support to write declarative layouts using data binding. This minimizes the necessary code in your application logic to connect to the user interface elements. The usage of data binding requires changes in your layout files. Such layout files starts with a layout root tag followed by a data element and a view root element.


1 Answers

Use import, not variable:

<data>
    <import type="yourfullpackagepath.Constants"/>
</data>
like image 93
Alan Todtenkopf Avatar answered Nov 15 '22 07:11

Alan Todtenkopf