... ... ...
Comme vous le savez, la liaison de données Librar y est une grande partie de la Jetpack Android bibliothèque pour réduire le code boilerplate et se lient vues aux données d'une manière plus efficace que ce qui était possible auparavant. Dans cet article, je vais expliquer comment nous pouvons utiliser la liaison de données dans nos vues personnalisées.
... ... ...
Début des travaux
, .., , , . , :
class MyCustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
init {
attrs?.let {
val typedArray =
context.obtainStyledAttributes(it, R.styleable.MyCustomView)
// some attr handling stuffs...
typedArray.recycle()
}
}
}
, .
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCustomView">
<attr name="currencyCode" format="string" />
</declare-styleable>
</resources>
, currencyCode
setCurrencyCode(arg)
, . , . , , .
. , @BindingMethods
, .
class MyCustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private val currencyFormatter = NumberFormat.getCurrencyInstance(Locale.getDefault())
//..
fun setCurrency(currencyCode: String?) {
if (currencyCode.isNullOrEmpty())
return
currencyFormatter.currency = Currency.getInstance(currencyCode)
}
//..
}
, , .
@BindingMethods(
value = [
BindingMethod(
type = MyCustomView::class,
attribute = "currencyCode",
method = "setCurrency"
)
]
)
class BindingMethods
.
, , .
@BindingAdapter(
value = ["paddingEnd", "paddingTop", "paddingStart", "paddingBottom"],
requireAll = false
)
fun MyCustomView.setPaddingRelative(
paddingEnd: Int = 0,
paddingTop: Int = 0,
paddingStart: Int = 0,
paddingBottom: Int = 0
) {
this.setPaddingRelative(paddingStart, paddingTop, paddingEnd, paddingBottom)
}
, .
. . .
, ! , , , !
- , Twitter.
"Android Developer. Professional".
: " coverage. Android //UI "