示例: 我们的产品需要向南非市场开放
配置环境
在build.gradle中加入支持
dataBinding {
enabled true
}
构建产品发布的model类
定义产品信息
data class ProductRelease(val country: String, val date: String, val version: String)
定义接口用来回调给主Fragment处理UI更改
interface OnViewChange {
fun onProductInfoChange(text: String)
}
在xml中使用DataBinding和model直接建立关系
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:bind="http://schemas.android.com/tools">
<data>
<variable
name="productT"
type="tv.rings.data.ProductRelease" />
<variable
name="onViewChange"
type="tv.rings.subscription.OnViewChange" />
</data>
具体的绑定xml
<android.support.constraint.ConstraintLayout
android:id="@+id/content_layout"
android:layout_width="match_parent"
android:layout_height="90dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="150dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="15dp"
android:background="@drawable/bg_rate_us"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
<Button
android:id="@+id/release_click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Release"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="15dp"
android:layout_marginTop="15dp"
app:layout_constraintTop_toTopOf="parent"
bind:onEvent="@{productT}"
bind:onChange="@{onViewChange}"/>
<TextView
android:id="@+id/release_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBaseline_toBaselineOf="@+id/release_click"
app:layout_constraintStart_toEndOf="@+id/release_click"/>
</android.support.constraint.ConstraintLayout>
其中productT
和onViewChange
是指你将要绑定的对象
Binding的实现类
object DataBindingAttrsUtils {
@JvmStatic
@BindingAdapter(value = ["onEvent", "onChange"], requireAll = false) // onEvent, onChange和xml里面bind:onEvent,bind:onChange,名字相对应
fun onEvent(releaseBtn: Button, product: ProductRelease, onViewChange: OnViewChange) { // product, onViewChange传递xml里@{对象}
releaseBtn.setOnClickListener {
onViewChange.onProductInfoChange("Release info:${product.country}, ${product.date}, ${product.version}")
}
}
}
requireAll 属性为false,表示在XML中,属性可以不用全部赋值,若是true,则attribute_name1~attribute_namen属性都要赋值,如果不设置,默认是true
主Fragment中实现了OnViewChange
接口,onProductInfoChange
里实现UI更改
override fun onProductInfoChange(text: String) {
releaseTv.text = text
}
主Fragment让xml和数据进行绑定
private lateinit var binding: FragmentSubscriptionBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_subscription, container, false)
return binding.root
}
绑定数据
val productRelease = ProductRelease("south_african", "2019.7.8", "1.1.3")
binding.productT = productRelease
binding.onViewChange = this
这样一个DataBinding结合kotlin在代码中的实现就完成了。