驴C贸mo utilizo el enlace de datos de Android en vistas personalizadas?

... ... ...





Como ya saben, el enlace de datos Librar y es una gran parte de la Android Jetpack biblioteca para reducir c贸digo repetitivo y se unen vistas a los datos de una manera m谩s eficiente que antes era posible. En este art铆culo, voy a explicar c贸mo podemos usar el enlace de datos en nuestras vistas personalizadas.





... ... ...





Inicio de obra

, .., , , . , :





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