在Android中如何使用DataBinding詳解(Kotlin)
前言
本問主要介紹DataBinding在Android App中的使用方法。數(shù)據(jù)綁定是將“提供器”的數(shù)據(jù)源與“消費者”綁定并使其同步的一種通用技術(shù)。
1. Android應(yīng)用程序使用數(shù)據(jù)綁定
1.1 介紹DataBinding
Android通過DataBinding提供了編寫聲明型布局的支持。這樣可以最大程度簡化布局和邏輯相關(guān)聯(lián)的代碼。
數(shù)據(jù)綁定要求修改文件,外層需要包裹一個layout布局。主要通過@{} 或 @={}語法把布局中的元素和表達式的引用寫入到屬性中。
<?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>
①用戶變量,定義了能在這個布局里面使用的屬性和類
②常規(guī)布局
DataBinding會基于layout創(chuàng)建一個Binding class,這個類包含了布局屬性(定義的變量)到相關(guān)視圖的所有綁定,并且會為布局中的數(shù)據(jù)元素生成setter,生成的類的名稱是基于layout的名稱(駝峰命名,加上Binding后綴)。比如布局名是activity_main.xml,生成的類就是ActivityMainBinding。你能通過這個類去inflate布局和數(shù)據(jù)模型,也可以通過DataBindingUtil類。
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點擊事件的處理
布局的處理除了數(shù)據(jù)的傳遞,還有點擊事件的處理。
使用方式和普通方法調(diào)用一樣。比如我在MainViewModel.kt中定義了getClick方法
fun getClick(v: View) {
//TODO
}
現(xiàn)在我想在Button點擊的時候調(diào)用getClick方法,只需要在布局文件中添加下面的代碼
android:onClick="@{(view) -> mainModel.getClick(view)}"
如果不需要參數(shù),可以直接
android:onClick="@{() -> mainModel.getClick()}"
如果有其他參數(shù),對應(yīng)的添加參數(shù)列表
android:onClick="@{() -> mainModel.getClick(args)}"
其他比如onLongClick之類的處理都是同理。
1.4 import的使用
可以通過import的方式導(dǎo)入類,直接調(diào)用類的靜態(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ù)實時刷新
當viewmodel的數(shù)據(jù)發(fā)生變化后,我們希望布局也同時刷新,有個非常簡單的方法,不需要繼承BaseObservable,我們通過引入LiveData來實現(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,無需通過observe監(jiān)聽,布局數(shù)據(jù)會自動刷新
}
fun getClick(v: View) {
getUserInfo()
}
}
1.6 使用BindingAdapter
可以通過BindingAdapter這個注解來實現(xiàn)屬性值變化的時候,控件狀態(tài)也跟著變化,比如圖片ImageView,當url變化的時候,控件會跟著顯示不同的圖片。
需要在靜態(tài)類里面定義一個靜態(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,這個可以直接指定控件的屬性,也可以自己定義屬性。
<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這個屬性,所以當這個屬性的值變化時會把view和url傳遞到loadImage。
如果是綁定的自定義字段呢?比如我現(xiàn)在綁定了一個自定義的url。
@BindingAdapter("url")
@JvmStatic fun loadImage(view: ImageView, url: String) {
...
}
那么布局文件就這么寫
<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é)
前面主要是寫了databinding的一些基本用法,擴展用法還比較多,我們后續(xù)再接著說。
到此這篇關(guān)于在Android中如何使用DataBinding(Kotlin)的文章就介紹到這了,更多相關(guān)Android使用DataBinding(Kotlin)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android自定義ViewGroup實現(xiàn)朋友圈九宮格控件
在我們的實際應(yīng)用中,經(jīng)常需要用到自定義控件,比如自定義圓形頭像,自定義計步器等等,這篇文章主要給大家介紹了關(guān)于Android自定義ViewGroup實現(xiàn)朋友圈九宮格控件的相關(guān)資料,需要的朋友可以參考下2021-07-07
Android開發(fā)之AlertDialog實現(xiàn)彈出對話框
這篇文章主要為大家詳細介紹了Android開發(fā)之AlertDialog實現(xiàn)彈出對話框,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-09-09
詳解Xamarin.Android 利用Fragment實現(xiàn)底部菜單
這篇文章主要介紹了詳解Xamarin.Android 利用Fragment實現(xiàn)底部菜單,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02

