数据绑定设置颜色

Shm*_*uel 2 data-binding android

我尝试使用三元运算符来更改按钮的文本颜色。类似这样的:这是 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)}"/>
Run Code Online (Sandbox Code Playgroud)

但颜色设置不正确。相反,我得到了一些奇怪的紫色。

我试过

<import type="com.myapp.R" />
android:textColor="@{selected ? R.color.white : R.color.turquoise}"
Run Code Online (Sandbox Code Playgroud)

结果相同。
我该怎么做呢?

Nik*_*lay 5

你的第一个变体应该可以正常工作。您可以参考本文档的“资源”章节。这是一个完整的工作示例。

颜色.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    ...
    <color name="foo">#fff</color>
    <color name="bar">#000</color>
</resources>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

ActivityMain.类

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);
    }
}
Run Code Online (Sandbox Code Playgroud)