[英]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.