Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ImageView bind srcCompact to a boolean Variable

I've just discovered how to bind variables to xml files, it's quite hard the first times but it really speed up the work.

How can I bind a variable to an imageView so that if the vabiable (boolean) goes from true to false the ImageView SrcCompact change as well?

<ImageView
    android:layout_width="48dp"
    android:layout_height="48dp"
    app:srcCompat="@drawable/ic_bluetooth_indigo_a400_48dp"
    android:id="@+id/imageView"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_margin="20dp" />

Here's my Imageview code with the BlueTooth Logo in Blue color. I'd like to bind it to a "BluetoothEnable" Boolean and, in case "BluetoothEnable" goes "FALSE" i want the imageView to show a SrcCompact with the Bluetooth Logo in red.

like image 913
L. Gangemi Avatar asked May 13 '26 08:05

L. Gangemi


1 Answers

I thought to share some solution if someone encounter this case.

When I tried to use the ternary expression, it didn't work for me:

<ImageView
    ...

    app:srcCompat="@{isBluetoothEnabled? @drawable/ic_bluetooth_green : @drawable/ic_bluetooth_red}"

    ... />

So, I tried the binding adapter approach.
Here I created a binding adapter, that will receive a boolean value for isBluetoothEnabled then based on it choose the proper drawable image:

public class BindingAdapters {

    @BindingAdapter("app:bluetoothBasedSrc")
    public static void setSendState(ImageView v, boolean isBluetoothEnabled) {
        int drawableRes = isBluetoothEnabled ? R.drawable.ic_bluetooth_green : R.drawable.ic_bluetooth_red;
        v.setImageResource(drawableRes);
    }

}

And here how we can use that binding adapter in the ImageView:

<ImageView
    ...

    app:bluetoothBasedSrc=@{isBluetoothEnabled}
    tools:srcCompat="@drawable/ic_bluetooth_green"

    ... />

Hope that solution helps this case.

like image 181
Ahmed Shendy Avatar answered May 14 '26 23:05

Ahmed Shendy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!