-
Notifications
You must be signed in to change notification settings - Fork 2
/
ObservableBackground.kt
101 lines (90 loc) · 2.8 KB
/
ObservableBackground.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package com.prilaga.verge_agni_yoga.view.view_model
import android.databinding.BaseObservable
import android.databinding.BindingAdapter
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import android.support.annotation.ColorRes
import android.support.annotation.DrawableRes
import android.support.v4.content.ContextCompat
import android.view.View
/**
* Created by Oleg Tarashkevich on 17.09.17.
*/
class ObservableBackground : BaseObservable() {
var mDrawableResource: Int? = null
private set
var mColorResource: Int? = null
private set
var mColorValue: Int? = null
private set
var mDrawable: Drawable? = null
private set
var mBitmap: Bitmap? = null
private set
private fun reset() {
mDrawableResource = null
mColorResource = null
mColorValue = null
mDrawable = null
}
fun setDrawableResource(@DrawableRes drawableResource: Int) {
reset()
mDrawableResource = drawableResource
notifyChange()
}
fun setColorResource(@ColorRes colorResource: Int) {
reset()
mColorResource = colorResource
notifyChange()
}
fun setColorValue(colorValue: Int) {
reset()
mColorValue = colorValue
notifyChange()
}
fun setDrawable(drawable: Drawable) {
reset()
mDrawable = drawable
notifyChange()
}
fun setBitmap(bitmap: Bitmap) {
reset()
mBitmap = bitmap
notifyChange()
}
fun clear() {
reset()
notifyChange()
}
}
@BindingAdapter("android:background")
fun setBackground(view: View, observable: ObservableBackground) {
if (observable.mDrawableResource != null)
observable.mDrawableResource?.let { view.setBackgroundResource(it) }
else if (observable.mColorResource != null)
observable.mColorResource?.let {
val color = ContextCompat.getColor(view.context, it)
view.setBackgroundColor(color)
}
else if (observable.mColorValue != null)
observable.mColorValue?.let { view.setBackgroundColor(it) }
else if (observable.mDrawable != null) {
observable.mDrawable?.let {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
view.setBackgroundDrawable(it)
else
view.background = it
}
} else if (observable.mBitmap != null) {
observable.mBitmap?.let {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
view.setBackgroundDrawable(BitmapDrawable(it))
else
view.background = BitmapDrawable(view.context.resources, it)
}
} else {
view.setBackgroundResource(0)
}
}