Use DataBinding library to set background color resource or null –

Question or issue in pp Development:

I would like to set background color or null on my view using DataBinding library but I get an exception trying to run it.

java.lang.NullPointerException: Attempt to invoke virtual method ‘int java.lang.Integer.intValue()’ on a null object reference

This is how I do it:

android:background=”@{article.sponsored ? @color/sponsored_article_background : null}”

I also tried setting conversion but it didn’t work.

@BindingConversion
public static ColorDrawable convertColorToDrawable(int color) {
return new ColorDrawable(color);
}

Eventually, I resolved it with workaround using @BindingAdapter but I would like to know how to do it properly.

How to solve this issue?

Solution no. 1:

Reason:

First thing to know is that DataBinding library already provides a convertColorToDrawable binding converter located in android.databinding.adapters.Converters.convertColorToDrawable(int).

Using android:background should “theoretically” work, because it has a corresponding setBackground(Drawable) method. The problem is that it sees that you try to pass a color as a first argument so it tried to launch this converter before applying it to setBackground(Drawable) method. If databinding decides to use a converter it will use it on both arguments, so also on null, right before applying a final result to a setter.
Because null cannot be castes to int (and you cannot invoke intValue() on it) it throws NullPointerException.

There is a mention about the fact that mixed argument types are not supported in official Data Binding Guide.

Here are two solutions for this problem. Although you can use any of these two solutions, the first one is much easier.

Solutions:

1. As drawable

If you define your color not as a color but as a drawable in your resources (it can be in our colors.xml file:

#your_color

or

@color/sponsored_article_background

then you should be able to use android:background like you originally wanted to but providing drawable instead of color:

android:background=”@{article.sponsored ? @drawable/sponsored_article_background : null}”

Here arguments has compatible types: first is Drawable and second is null so it can also be cast to a Drawable.

2. As resource id

app:backgroundResource=”@{article.sponsored ? R.color.sponsored_article_background : 0}”

but it will also require to add your R class import in data section:

Passing 0 as a “null resource id” is safe because setBackgroundResource method of View checks whether resid is different than 0 and sets null as a background drawable otherwise. No unnecessary transparent drawable objects are created there.

public void setBackgroundResource(int resid) {
if (resid != 0 && resid == mBackgroundResource) {
return;
}

Drawable d= null;
if (resid != 0) {
d = mResources.getDrawable(resid);
}
setBackgroundDrawable(d);

mBackgroundResource = resid;
}

Solution no. 2:

I think you have to try default color instead of null

like this

android:background=”@{article.sponsored ? @color/sponsored_article_background : @color/your_default_color}”

Solution no. 3:

One approach you can use is to write a custom @BindingConversion to take care of this for you:

@BindingConversion
public static ColorDrawable convertColorToDrawable(int color) {
return color != 0 ? new ColorDrawable(color) : null;
}

With this, you can set any attribute that accepts a ColorDrawable to an integer color value (like 0 or @android:color/transparent) and have it automatically converted to the lightweight @null for you.

(Whereas the built-in convertColorToDrawable(int) convertor always creates a ColorDrawable object, even if the color is transparent.)

Note: in order for this method to be used in place of the built-in @BindingConversion, it must return a ColorDrawable and not a Drawable — otherwise the built-in method will be seen as more specific/appropriate.

Another approach is to use a static method to convert from a color to a Drawable within your data binding expression, in order to make the value types match. For example, you could import the built-in Converters class:

…and write your expression like this:

android:background=”@{article.sponsored ? Converters.convertColorToDrawable(@color/sponsored_article_background) : null}”

…although I would personally recommend putting this kind of conditional logic in your data binding adapter method instead, e.g. using a getArticleBackground() method that returns a Drawable or null. In general things are easier to debug and keep track of if you avoid putting decision logic within your layout files.

Solution no. 4:

Try this:

@Bindable
private int color;

and in constructor

color = Color.parseColor(“your color in String for examp.(#ffffff)”)

in xml:

android:textColor = “@{data.color}”

Solution no. 5:

In this article you can find two good solutions, in my case though, only one of work because I wanted to change background tint in a Material Button, here’s my Binding adapter:

First, create a Kotlin file and paste this adapter method:

package com.nyp.kartak.utilities

import android.content.res.ColorStateList
import androidx.databinding.BindingAdapter
import com.google.android.material.button.MaterialButton
import com.nyp.kartak.model.ReceiptUserPurchaseModel

@BindingAdapter(“backgroundTintBinding”)
fun backgroundTintBinding(button: MaterialButton, model: ReceiptUserPurchaseModel) {
button.backgroundTintList = ColorStateList.valueOf(button.resources.getColor( model.color))
}

Second use it in your xml:

// …..

Solution no. 6:

It’s really old post but I want to suggest one more solution.

  1. DECLARE CUSTOM STYLES/BACKGROUNDS IN DRAWABLE**

I have four similar styles so I’ll paste just one of them.

When I’ll set this style my button look like below:

enter image description here

  1. Prepare bindable value in your model/handler class

In my case I have below code in ActivityMainEventHandler class

@Bindable
public Drawable getConenctButtonStyle() {
// here i’m checking connection state but you can do own conditions
ConnectionState state = Communication.getInstance().getConnectionState();
if (state != null) switch (state) {
case CONNECTED:
return ctx.getDrawable(R.drawable.circle_btn_state_green);
case CONNECTING:
case DISCONNECTING:
return ctx.getDrawable(R.drawable.circle_btn_state_orange);
case DISCONNECTED:
return ctx.getDrawable(R.drawable.circle_btn_state_red);
}
return ctx.getDrawable(R.drawable.circle_btn_state_first);
}

  1. Pass your class to the your view

Activity onCreate:

bind = DataBindingUtil.setContentView(this, R.layout.activity_main);
handler = new ActivityMainEventHandler(this, bind);
bind.setMainHandler(handler);

XML of our activity

  1. Set your background to view as below

Markup:

android:background=”@{mainHandler.conenctButtonStyle}”

  1. Then if you want check conditions of step2 again and redraw view just call

Code:

//BR.conenctButtonStyle it’s automatically generated id
bind.notifyPropertyChanged(BR.conenctButtonStyle);

Solution no. 7:

Another solution for this, if you just want to set backgroundTint, but not whole background, you can use it like this:

You will need to import ContextCompat, if your min api is 21:

app:backgroundTintList=”@{ContextCompat.getColorStateList(context, [funtion_to_get_your_color_res_id]))}”

Good Luck!

Related Tags:

bindingadapter,android-databinding drawable resource,android data binding text color,databinding kotlin,android bindingadapter attribute not found,android binding adapter multiple parameters,android databinding onclick,data binding binding adapters,android view binding,string resource databinding,databinding set resource id

Leave a comment

Your email address will not be published. Required fields are marked *