簡體   English   中英

如何在自定義視圖Android中使用數據綁定

[英]How to use Data Binding with custom view Android

這是我的自定義視圖.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>

    <variable
        name="viewModel"
        type="com.viewModel.ViewModel" />

</data>

<RelativeLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <com.views.MyView
        app:length="@{viewModel.codeLenght}"
        app:success_color="@drawable/border_green_fill_white"
        app:width="@dimen/icon_size_huge" />
</RelativeLayout>

這是我的看法:

class MyView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0) : FrameLayout(context, attrs, defStyleAttr){

init {
    val styles = context.obtainStyledAttributes(attrs, R.styleable.CodeTextView)
    styleEditTexts(styles, attrs)
    styles.recycle()
}

private fun styleEditTexts(styles: TypedArray, attrs: AttributeSet?) {
    length = styles.getInt(R.styleable.AttrView_length, DEFAULT_LENGTH)
    generateViews(styles, attrs)
}

@BindingAdapter("app:length")
fun setLength(view: CodeTextView, size: Int) {
    view.length = size
}

如何從ViewModel獲取長度值

您可以使用context以與在Activity / Fragment相同的方式在MyView中獲取ViewModel類。

ViewModelProvider(context as YourActivity)[ViewModel::class.java]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM