1

I use data binging in a view holder of a recycler view. For showing an inactive row, I set foreground to a color and this is working perfect on my Nexus6 and many other devices.

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white"
    android:foreground="@{subscribed.isAutoRenew() ? @color/transparent : @color/bg_inactive}">
        other stuff ...
</RelativeLayout>

The problem is this code is not working on Samsung SM-N900 with android 5.0. I can solve it by using java code instead of data binding. Any suggestion how to solve it by data binding?

hadilq
  • 1,023
  • 11
  • 25
  • 1
    Would you mind posting what java code you're using that works? Data binding will be using the equivalent of `view.setForeground(new ColorDrawable(view.getResources().getColor(R.color.transparent)))`. If your java code differs, try that java code out and see if it fails as well. – George Mount Feb 12 '17 at 00:59
  • I used the same code as you mentioned and it's working. I should mention here that I wrapped the relative layout with a frame layout because setForground method of relative layout requires API level 23. – hadilq Feb 12 '17 at 08:30

1 Answers1

1

Data binding avoids method calls that don't exist on older platforms. If the device that you're testing on is older than API 23 (Marshmallow), then it will refuse to call setForeground(). Data Binding doesn't have a magical way to give the RelativeLayout the foreground capability, so you'll have to do what you do in the Java Code. Give your layout a FrameLayout wrapper and assign the foreground to it.

<FrameLayout ... 
    android:foreground="@{subscribed.isAutoRenew() ? @color/transparent : @color/bg_inactive}">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white">
    other stuff ...
    </RelativeLayout>
</FrameLayout>

-- edit --

Based on the comment, I must conclude that there must be a bug in Data Binding in which it detects the version of View.setForeground() and sees that it is API 23, so skips it. It must not be checking FrameLayout.setForegound(). I'll file a bug on this.

In the mean time, you can work around it by creating your own BindingAdapter:

@BindingAdapter("android:foreground")
public static void setForeground(FrameLayout view, Drawable drawable) {
    view.setForeground(drawable);
}
George Mount
  • 20,708
  • 2
  • 73
  • 61
  • As I commented above, I did test it, and it didn't work in that special device. So I had to implement it in java code. – hadilq Feb 13 '17 at 07:12
  • Thanks for the BindingAdapter! Strangely I did not need it using Android Studio (3.0.1), but in Intellij (2017.2.5) it was necessary! Very same PC and identical code. Strange. – Dominikus K. Dec 21 '17 at 13:26