How do I use Android Data Binding in custom views?

... ... ...





, Data Binding Library - Android Jetpack, , . , .





.     .     .





, .., , , . , :





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 "





  • . 1





  • . 2









All Articles