How can use ?attr/colorAccent in databinding expressions?

Viewed 566

I have a XML field that I want to change based on an 'ObservableBoolean' like this:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    >
  <data>
    <variable
        name="isColored"
        type="androidx.databinding.ObservableBoolean"
        />
  </data>
  <androidx.constraintlayout.widget.ConstraintLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      >
    <com.consoleco.console.customView.PerTextView
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:background="@{isColored ? ?attr/colorAccent : @color/grayBackground"
        android:gravity="center"
        android:text="@string/save"
        android:textColor="@color/white"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        />
  </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

In this line of code above:

android:background="@{isColored ? ?attr/colorAccent : @color/grayBackground"

we can't use two '?' mark (IDE give error: expected, got ?' How can I resolve this problem?

2 Answers

You can use a BindingAdapter for this (add this in a class):

@BindingAdapter("isColored")
public static void isColored(View view, boolean isColored){
    TypedValue typedValueColor = new TypedValue();
    view.getContext().getTheme().resolveAttribute(R.attr.colorAccent, typedValueColor, true);
    if(isColored){
        view.setBackground(typedValueColor.data);
    } else {
        view.setBackground(view.getContext().getResources().getColor(R.color.grayBackground));
    }
}

And in your xml layout replace this:

android:background="@{isColored ? ?attr/colorAccent : @color/grayBackground"

With this:

app:isColored="@{isColored}"

Yes that is true. you can not use ?attr in your expression.

For now only work you can do is use @color/colorAccent instead of ?attr/colorAccent

Related