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. I believe binding adapter would work but not sure how to write it. How can I write binding adapter for the same?
            Asked
            
        
        
            Active
            
        
            Viewed 1,206 times
        
    2 Answers
2
            
            
        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)
}
        krai29
        
- 153
 - 3
 - 16
 
0
            
            
        I ran into this same problem a few months back. what I did was stored the data coming from API to one POJO class. Then in an XML file using that POJO class member as data binding variable. i.e.
<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) {
}
        Urvish rana
        
- 601
 - 10
 - 24
 
- 
                    I am storing the data in POJO class. The background colour is coming in hex code without the "#". I tried the following: – krai29 Feb 11 '19 at 09:31
 - 
                    app:background = "@{'#'+var.color}" . This didn't work – krai29 Feb 11 '19 at 09:33
 - 
                    Does it work with a custom getter, e.g: getFullColor() which returns the color code including the hashtag ? Sorry, I'm not yet familiar with databinding. – Ariles Feb 11 '19 at 09:42
 - 
                    @humbleDev read the last line of XML file its custom binding. Use custom binding it'll work and you got color in a simple string from right?.there is no direct API for setting background color dynamically passing the hex code. you need to use setBackgroungResource() for that – Urvish rana Feb 11 '19 at 09:43
 - 
                    follow this quetion for that https://stackoverflow.com/q/1466788/7271231 – Urvish rana Feb 11 '19 at 09:44
 - 
                    Color is coming in this form FFF9E6. I am not sure what you meant by status of type boolean. Could you help me by providing me solution in my case? – krai29 Feb 11 '19 at 09:52
 - 
                    hi, I've updated the answer. in the function body, you need to put the following logic which is given in the answer. https://stackoverflow.com/a/39817392/7271231 – Urvish rana Feb 11 '19 at 10:02