Kotlin的最小数据绑定示例

时间:2020-03-30 23:43:58

标签: android kotlin data-binding

我看了几个例子,但是它们要么抽象太多,要么教程过时。我想以最小的方式实现此功能。在这里,我需要使用User作为Navigational体系结构中的参数传递的UserForm类的帮助。

模块化应用程序build.gradle ,我已添加

android {
    ...
    dataBinding {
        enabled = true
    }
}

用户

@Parcelize
data class User(var first: String, var last: String): Parcelable

FormFragment.kt

class UserForm: Fragment() {

    private val user by lazy {
        arguments?.getParcelable("user") ?: User("John", "Doe")
    }   

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_form, container, false)
    }
}

fragment_form.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <variable name="user" type="data.User" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <EditText
                android:id="@+id/first"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:ems="10"
                android:inputType="text"
                android:text="@{user.first}" />

        <EditText
                android:id="@+id/last"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:ems="10"
                android:inputType="text"
                android:text="@{user.last}" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

一些摘要

1 个答案:

答案 0 :(得分:1)

在下面修改您的代码:

FormFragment.kt

class UserForm: Fragment() {

    private val user by lazy {
        arguments?.getParcelable("user") ?: User("John", "Doe")
    }   

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val binding = FragmentFormBinding.inflate(inflater, container, false).apply {
            user = this@UserForm.user
        }
        return binding.root
    }
}

说明:

  1. 由于您在fragment_form.xml中使用了DataBinding,因此将自动生成相应的FragmentFormBinding类

  2. 我们通常使用XxxBinding.inflate代替inflater.inflate(layoutid,container,false)

  3. 在FragmentFormBinding.inflate之后,我们将用户对象绑定到fragment_form.xml

相关问题