在Android中如何使用DataBinding詳解(Kotlin)
前言
本問(wèn)主要介紹DataBinding在Android App中的使用方法。數(shù)據(jù)綁定是將“提供器”的數(shù)據(jù)源與“消費(fèi)者”綁定并使其同步的一種通用技術(shù)。
1. Android應(yīng)用程序使用數(shù)據(jù)綁定
1.1 介紹DataBinding
Android通過(guò)DataBinding提供了編寫(xiě)聲明型布局的支持。這樣可以最大程度簡(jiǎn)化布局和邏輯相關(guān)聯(lián)的代碼。
數(shù)據(jù)綁定要求修改文件,外層需要包裹一個(gè)layout布局。主要通過(guò)@{} 或 @={}語(yǔ)法把布局中的元素和表達(dá)式的引用寫(xiě)入到屬性中。
<?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"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="mainModel"
type="me.ithome.jetpack.model.MainViewModel" />①
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">②
<TextView
android:id="@+id/tv_userinfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{mainModel.userData.toString()}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="56dp"
android:onClick="@{(view) -> mainModel.getClick(view)}"
android:text="@string/btn_getUserInfo"
app:layout_constraintBottom_toTopOf="@+id/tv_userinfo"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
①用戶(hù)變量,定義了能在這個(gè)布局里面使用的屬性和類(lèi)
②常規(guī)布局
DataBinding會(huì)基于layout創(chuàng)建一個(gè)Binding class,這個(gè)類(lèi)包含了布局屬性(定義的變量)到相關(guān)視圖的所有綁定,并且會(huì)為布局中的數(shù)據(jù)元素生成setter,生成的類(lèi)的名稱(chēng)是基于layout的名稱(chēng)(駝峰命名,加上Binding后綴)。比如布局名是activity_main.xml,生成的類(lèi)就是ActivityMainBinding。你能通過(guò)這個(gè)類(lèi)去inflate布局和數(shù)據(jù)模型,也可以通過(guò)DataBindingUtil類(lèi)。
DataBindingUtils加載布局
val mainBindingUtil = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main) mainBindingUtil.lifecycleOwner = this
inflate加載布局(此方法也能用于RecyclerView, ViewPager)
val mainBindingUtil = ActivityMainBinding.inflate(layoutInflater) setContentView(mainBindingUtil.root)
上述兩種方法大家二選一,一般在Activity中我們都用第一種。
1.2 如何啟用DataBinding
想要在Android App工程中使用databinding,只需要在app/build.gradle文件中設(shè)置如下代碼:
android {
....
dataBinding {
enabled = true
}
}
1.3 DataBinding點(diǎn)擊事件的處理
布局的處理除了數(shù)據(jù)的傳遞,還有點(diǎn)擊事件的處理。
使用方式和普通方法調(diào)用一樣。比如我在MainViewModel.kt中定義了getClick方法
fun getClick(v: View) {
//TODO
}
現(xiàn)在我想在Button點(diǎn)擊的時(shí)候調(diào)用getClick方法,只需要在布局文件中添加下面的代碼
android:onClick="@{(view) -> mainModel.getClick(view)}"
如果不需要參數(shù),可以直接
android:onClick="@{() -> mainModel.getClick()}"
如果有其他參數(shù),對(duì)應(yīng)的添加參數(shù)列表
android:onClick="@{() -> mainModel.getClick(args)}"
其他比如onLongClick之類(lèi)的處理都是同理。
1.4 import的使用
可以通過(guò)import的方式導(dǎo)入類(lèi),直接調(diào)用類(lèi)的靜態(tài)方法。
<data>
<import type="me.ithome.jetpack.utils.StringUtils" />
<variable
name="mainModel"
type="me.ithome.jetpack.model.MainViewModel" />
</data>
<TextView
android:text="@{StringUtils.capitalize(mainModel.userData.name)}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
1.5 數(shù)據(jù)實(shí)時(shí)刷新
當(dāng)viewmodel的數(shù)據(jù)發(fā)生變化后,我們希望布局也同時(shí)刷新,有個(gè)非常簡(jiǎn)單的方法,不需要繼承BaseObservable,我們通過(guò)引入LiveData來(lái)實(shí)現(xiàn)。
open class MainViewModel : ViewModel() {
var userData: MutableLiveData<UserInfo> = MutableLiveData()
init {
getUserInfo()
}
private fun getUserInfo() {
val user = UserInfo("李四", (10..50).random())
userData.postValue(user) //數(shù)據(jù)發(fā)生變化后,調(diào)用postValue,無(wú)需通過(guò)observe監(jiān)聽(tīng),布局?jǐn)?shù)據(jù)會(huì)自動(dòng)刷新
}
fun getClick(v: View) {
getUserInfo()
}
}
1.6 使用BindingAdapter
可以通過(guò)BindingAdapter這個(gè)注解來(lái)實(shí)現(xiàn)屬性值變化的時(shí)候,控件狀態(tài)也跟著變化,比如圖片ImageView,當(dāng)url變化的時(shí)候,控件會(huì)跟著顯示不同的圖片。
需要在靜態(tài)類(lèi)里面定義一個(gè)靜態(tài)方法:
object StringUtils {
@BindingAdapter("android:src")
@JvmStatic fun loadImage(view: ImageView, url: String) {
MyApplication._context?.let {
Glide.with(it)
.load(url)
.into(view)
}
}
}
注意這里的android:src,這個(gè)可以直接指定控件的屬性,也可以自己定義屬性。
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tv_userinfo"
android:src="@{mainModel.imageUrl}"
tools:srcCompat="@tools:sample/avatars" />
loadImage方法綁定的是android:src這個(gè)屬性,所以當(dāng)這個(gè)屬性的值變化時(shí)會(huì)把view和url傳遞到loadImage。
如果是綁定的自定義字段呢?比如我現(xiàn)在綁定了一個(gè)自定義的url。
@BindingAdapter("url")
@JvmStatic fun loadImage(view: ImageView, url: String) {
...
}
那么布局文件就這么寫(xiě)
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tv_userinfo"
app:url="@{mainModel.imageUrl}"
tools:srcCompat="@tools:sample/avatars" />
總結(jié)
前面主要是寫(xiě)了databinding的一些基本用法,擴(kuò)展用法還比較多,我們后續(xù)再接著說(shuō)。
到此這篇關(guān)于在Android中如何使用DataBinding(Kotlin)的文章就介紹到這了,更多相關(guān)Android使用DataBinding(Kotlin)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android天氣預(yù)報(bào)app改進(jìn)版
這篇文章主要為大家詳細(xì)介紹了改進(jìn)版的Android天氣預(yù)報(bào)app,內(nèi)容更加充實(shí),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-07-07
Android開(kāi)發(fā)筆記XML數(shù)據(jù)解析方法及優(yōu)缺點(diǎn)
XML數(shù)據(jù)是一種常見(jiàn)的數(shù)據(jù)格式,Android開(kāi)發(fā)中需要對(duì)其進(jìn)行解析。常用的XML解析方式有DOM、SAX、Pull和Json等,每種方式都有其優(yōu)缺點(diǎn)。開(kāi)發(fā)者可以根據(jù)具體需求選擇合適的解析方式,提高數(shù)據(jù)解析效率和性能2023-05-05
Android自定義View實(shí)現(xiàn)水波紋引導(dǎo)動(dòng)畫(huà)
這篇文章主要為大家詳細(xì)介紹了Android自定義View實(shí)現(xiàn)水波紋動(dòng)畫(huà)引導(dǎo),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01
Flutter進(jìn)階之實(shí)現(xiàn)動(dòng)畫(huà)效果(九)
這篇文章主要為大家詳細(xì)介紹了Flutter進(jìn)階之實(shí)現(xiàn)動(dòng)畫(huà)效果的第九篇,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-08-08
Android 中 ActivityLifecycleCallbacks的實(shí)例詳解
這篇文章主要介紹了Android 中 ActivityLifecycleCallbacks的實(shí)例詳解的相關(guān)資料,希望通過(guò)本文大家能掌握這部分內(nèi)容,需要的朋友可以參考下2017-09-09
Android檢測(cè)手機(jī)多點(diǎn)觸摸點(diǎn)數(shù)的方法
這篇文章主要為大家詳細(xì)介紹了Android檢測(cè)手機(jī)多點(diǎn)觸摸點(diǎn)數(shù)的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05
Android Selector獲取焦點(diǎn)后文本背景修改的實(shí)現(xiàn)代碼
這篇文章主要介紹了Android Selector獲取焦點(diǎn)后文本背景修改的實(shí)現(xiàn)代碼,本文通過(guò)demo展示和實(shí)現(xiàn)代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-11-11
Android中TextView局部變色功能實(shí)現(xiàn)
這篇文章給大家詳細(xì)講解了一下Android中TextView實(shí)現(xiàn)部分文字不同顏色的功能實(shí)現(xiàn)過(guò)程,有這方面需要的朋友們一起學(xué)習(xí)下吧。2017-12-12

