6

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?

Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212

2 Answers2

14

Use import, not variable:

<data>
    <import type="yourfullpackagepath.Constants"/>
</data>
Alan Todtenkopf
  • 452
  • 4
  • 6
5

Import the class where your public or internal constant is present:

<data>
    <import type="com.ananth.nasaphotooftheday.utility.Constant"/>
    <variable
        name="viewModel"
        type="com.ananth.nasaphotooftheday.ui.main.MainViewModel" />
</data>

Use it according to your use, for example:

<ImageView
        android:id="@+id/image_fullscreen"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:src="@{(viewModel.media.type == Constant.MEDIA_TYPE_IMAGE) ? @drawable/ic_play : @drawable/ic_fullscreen}"
        android:layout_marginEnd="@dimen/spacing_large" />
Ananth
  • 2,597
  • 1
  • 29
  • 39