简体   繁体   English

当颜色来自api作为十六进制代码时,如何编写绑定适配器来设置背景颜色?

[英]How to write binding adapter to set background colour when the colour is coming from api as hex code?

Background colour is coming from API in this form FFF9E6.I am using data binding.I am not able to understand how I can set it as background colour. 背景颜色来自API以这种形式FFF9E6.我正在使用数据绑定。我无法理解如何将其设置为背景颜色。 I believe binding adapter would work but not sure how to write it. 我相信绑定适配器可以工作,但不知道如何写它。 How can I write binding adapter for the same? 我怎么能写相同的绑定适配器?

I ran into this same problem a few months back. 几个月前我遇到了同样的问题。 what I did was stored the data coming from API to one POJO class. 我所做的是将来自API的数据存储到一个POJO类中。 Then in an XML file using that POJO class member as data binding variable. 然后在一个XML文件中使用该POJO类成员作为数据绑定变量。 ie

<TextView
            android:layout_width="0dp"
            android:layout_height="60dp"
            android:layout_margin="@dimen/_8dp"
            android:layout_weight="1"
            android:gravity="center"
            android:padding="@dimen/_8dp"
            app:color="@{item.color}" />

and it's binding adapter 它是绑定适配器

@BindingAdapter("bind:color")
public static void setStatus(TextView textView, String color) {

}

This code worked in my case. 这段代码适用于我的情况。

@BindingAdapter("android:backgroundColor")
fun ViewGroup.setBackground(backgroundColor: String) {

val color: Int = try {
    Color.parseColor(background)
} catch (e: Exception) {
    Color.parseColor("#$background")
}
setBackgroundColor(color)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM