Search code examples
androiddata-binding

Data binding setting colors


I try to use ternary operator to change the textcolor of button. Something like that: here is the xml.

<Button
    android:id="@+id/actionButton"
    android:layout_width="113dp"
    android:layout_height="30dp"
    android:background="@drawable/button"
    android:backgroundTint="@{selected ? R.color.white : R.color.turquoise}"
    android:text="@{selected ? &quot;Selected &quot; : &quot;Select &quot;}"
    android:textColor="@{selected ? @color/white : @color/turquoise}"
    android:onClick="@{(view) -> handler.selectClick(view)}"/>

But the colors are not set correctly. I get some wierd purple colors instead.

I tried

<import type="com.myapp.R" />
android:textColor="@{selected ? R.color.white : R.color.turquoise}"

with same result.
How should I do it?


Solution

  • Your first variant should work fine. You can refer to "Resources" chapter of this doc. Here is a full working example.

    colors.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        ...
        <color name="foo">#fff</color>
        <color name="bar">#000</color>
    </resources>
    

    main_activity.xml

    <?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android">
    
        <data>
            <variable name="selected" type="boolean" />
            <variable name="button2" type="String" />
        </data>
    
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
    
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/btn_a"
                android:onClick="switchColor"
                android:text="Click me"/>
    
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/btn_b"
                android:textColor="@{selected ? @color/foo : @color/bar}"
                android:text="@{button2}"/>
    
        </LinearLayout>
    </layout>
    

    ActivityMain.class

    public class ActivityMain extends AppCompatActivity {
    
        public static final String TAG = "MainActivity";
    
        MainActivityBinding mBinding;
        boolean mSelected;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mBinding = DataBindingUtil.setContentView(this, R.layout.main_activity);
            mBinding.setButton2("Don't click me please!");
        }
    
        public void switchColor(View view) {
            mBinding.setSelected(mSelected = !mSelected);
        }
    }