溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

DataBinding如何在Android中使用

發(fā)布時(shí)間:2020-11-10 15:08:01 來源:億速云 閱讀:189 作者:Leah 欄目:開發(fā)技術(shù)

DataBinding如何在Android中使用?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

1. Android應(yīng)用程序使用數(shù)據(jù)綁定

1.1 介紹DataBinding

Android通過DataBinding提供了編寫聲明型布局的支持。這樣可以最大程度簡化布局和邏輯相關(guān)聯(lián)的代碼。
數(shù)據(jù)綁定要求修改文件,外層需要包裹一個(gè)layout布局。主要通過@{} 或 @={}語法把布局中的元素和表達(dá)式的引用寫入到屬性中。

<&#63;xml version="1.0" encoding="utf-8"&#63;>
<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>

①用戶變量,定義了能在這個(gè)布局里面使用的屬性和類

②常規(guī)布局

DataBinding會(huì)基于layout創(chuàng)建一個(gè)Binding class,這個(gè)類包含了布局屬性(定義的變量)到相關(guān)視圖的所有綁定,并且會(huì)為布局中的數(shù)據(jù)元素生成setter,生成的類的名稱是基于layout的名稱(駝峰命名,加上Binding后綴)。比如布局名是activity_main.xml,生成的類就是ActivityMainBinding。你能通過這個(gè)類去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點(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之類的處理都是同理。

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ù)實(shí)時(shí)刷新

當(dāng)viewmodel的數(shù)據(jù)發(fā)生變化后,我們希望布局也同時(shí)刷新,有個(gè)非常簡單的方法,不需要繼承BaseObservable,我們通過引入LiveData來實(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,無需通過observe監(jiān)聽,布局?jǐn)?shù)據(jù)會(huì)自動(dòng)刷新
  }

  fun getClick(v: View) {
    getUserInfo()
  }
}

1.6 使用BindingAdapter

可以通過BindingAdapter這個(gè)注解來實(shí)現(xiàn)屬性值變化的時(shí)候,控件狀態(tài)也跟著變化,比如圖片ImageView,當(dāng)url變化的時(shí)候,控件會(huì)跟著顯示不同的圖片。

需要在靜態(tài)類里面定義一個(gè)靜態(tài)方法:

object StringUtils {

  @BindingAdapter("android:src")
  @JvmStatic fun loadImage(view: ImageView, url: String) {
    MyApplication._context&#63;.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) {
...
}

那么布局文件就這么寫

<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" />

看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI