Jetpack DataBinding

See also README in https://github.com/lingxuxiong/JetpackGo2/tree/databinding

Introduction

The Data Binding Library is a support library that allows you to bind
UI components in your layouts to data sources in your app using a
declarative format rather than programmatically.

Assumptions

  • Android Studio IDE: v4.1.1
  • Android Gradle Plugin: v4.1.1
  • Kotlin & Plugin Version: 1.4.10

Terms And Abbr.

  • View Binding (VB)

Binding layout views that has a unique ID to a generated file so that
the views can be accessed handily. It can be replacement findViewById calls.

  • Data Binding (DB)

Binding layout views to model objects so that the bound objects can be
changed directly from the layout, and vice versus, changes on the objects
can be applied to the layout views automatically. Data Binding can be
one-way (V -> M) or Two-way (V <-> M), depending on the binding expression
used. @{} for one-way binding and @={} for two-way binding, respectively.

While the two-way binding is expected most of the time and it requires the
model data observable and wrapped with LiveData. As we can see,
one-way binding is kind of static binding, whereas two-way binding
is dynamic binding.

  • Observability

Objects that are observable and are capable of notifying UI updates. It
can be implemented as observable fields, Live Data, or observable classes.

How to use

  1. Enable data-binding from the app Gradle file
plugins {
    // If you plan to use data binding in a Kotlin project, 
    // you should apply the kotlin-kapt plugin
    id 'kotlin-kapt'
}

android {
    // before AGP 4
    buildFeatures {
        dataBinding true
    }
}

Or

    // on before AGP 4+
    dataBinding {
        enabled true
    }
  1. Covert regular layout file to data binding layout Shortcut:
    right-click on the root element of the layout file, then choose
    "Convert to data binding layout"

  2. Inflates root view in a data binding way.

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding: ActivityMainBinding = DataBindingUtil.setContentView(
            this, R.layout.activity_main)
        binding.greeting = "Hello DataBinding"
    }
  1. Changes the value of variables bound
binding.greeting = "Hello DataBinding"

Note: As view binding can coexist with data binding, so be careful enough to NOT mix a VB variable with a DB variable, otherwise you might not get the expected results. For example:

binding.name = viewModel.name             // assigns to a DB String variable, named `name`, supporting two-way binding. -> UI will refresh accordingly
binding.plain_name.text = viewModel.name  // assigns to a VB TextView variable, named `plain_name`, supporting only one-way binding. -> UI won't refresh accordingly

  1. Steps to implement ViewModel binding
  • Adds dependencies to lifecycle View Model, if not yet
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
  • Creates custom ViewModel class
class GreetingViewModel: ViewModel() {

    private val _greeting = MutableLiveData("Hello data binding")
    val greeting: LiveData<String> = _greeting

    fun changeGreeting(greetingMessage: String) {
        _greeting.value = greetingMessage
    }
}
  • Declares ViewModel variable
    <data>
        <variable name="vm" type="vm.GreetingViewModel" />
    </data>
  • Uses layout expression to change view attributes
    <TextView>
        android:text="@{vm.greeting}"
    </TextView>
  • Inflates and binds ViewModel object
    private val viewModel: GreetingViewModel by lazy {
        ViewModelProvider(this).get(GreetingViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding: ActivityMainBinding = DataBindingUtil.setContentView(
            this, R.layout.activity_main)
        binding.vm = viewModel
    }
  • Changes ViewModel value to refresh UI
    override fun onResume() {
        super.onResume()
        viewModel.changeGreeting("Changed greeting: Haha")
    }
  • Accepts user input (e.g. click event) and refresh UI elements accordingly
    • Defines responding function
          fun changeRandomGreeting() {
            val idx = Random.Default.nextInt(famousSayings.size)
            _greeting.value = famousSayings[idx]
        }
      
    • Binds the responding function to specific user event
          <TextView>
              android:onClick="@{() -> vm.changeRandomGreeting()}"
          </TextView>
      
    • Adds lifecycle owner of the binding
          override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          val binding: ActivityMainBinding = DataBindingUtil.setContentView(
              this, R.layout.activity_main)
      
          binding.vm = viewModel
      
          // Sets the {@link LifecycleOwner} that should be used for observing changes of
          // LiveData in this binding. If a {@link LiveData} is in one of the binding expressions
          // and no LifecycleOwner is set, the LiveData will not be observed and updates to it
          // will not be propagated to the UI. check ViewDataBinding.setLifecycleOwner() for more details
          binding.lifecycleOwner = this
      }
      

      Note: If failing to add binding lifecycle then the UI won't get refreshed.

References

  1. Android Doc. Data Binding Library Overview. 12/08/2020
  2. Jose Alcérreca(Jalc). Codelabs - Data Binding in Android. 12/08/2020
  3. Jose Alcérreca(Jalc), Jeremy Walker. Android Data Binding Library samples. 12/09/2020
  4. Jose Alcérreca(Jalc). Android Data Binding Library — from Observable Fields to LiveData in two steps. 12/08/2020
  5. Google Git. Databinding Adapters Classes List. 12/09/2020
  6. Chris Banes. Data Binding — lessons learned. 12/09/2020

Q & A

  1. What's Data Binding Layout

    The layout file with data binding enabled. It consists of two sections -
    the data section and view section, for layout variables and UI elements, respectively.

    <layout>
       <data>
         <!-- definition of data variables goes here -->
       </data>
       
       <ViewRoot>
         <!-- view declaration goes here --> 
       </ViewRoot>
    </layout>
    
  2. What's Layout Variable

    Variables defined in the layout file and used to bilaterally exchange
    info between the model and view.

  3. What's Binding Expression

    An regular Kotlin/Java expression that starts with a @ sign and is
    wrapped inside curly braces {}. It operates on layout variables and is
    placed in the layout file as applicable element attribute values.

    Basic expression examples:

    <!-- Some examples of complex layout expressions -->
    <TextView>
        android:text="@{String.valueOf(index + 1)}"
        android:visibility="@{age < 13 ? View.GONE : View.VISIBLE}"
        android:transitionName='@{"image_" + id}'
    </TextView>
    

    ViewModel-bound expression examples:

    <TextView>
        android:text="@{viewmodel.name}"
        <!-- Bind the nameVisible property of the viewmodel to the visibility attribute -->
        android:visibility="@{viewmodel.nameVisible}"
        <!-- Call the onLike() method on the viewmodel when the View is clicked. -->
        android:onClick="@{() -> viewmodel.onLike()}"
    </TextView>
    
  4. What's Binding Adapter

    Binding Adapter is a @BindingAdapter annotated static method which
    gets called WHEN the binding variable get changed to update the target
    view defined by this adapter. For example:

    Definitions of binding adapter

        // This is a built-in binding adapter
        @BindingAdapter("android:text")  // 1
        @JvmStatic fun setText(view: TextView, text: CharSequence) { // 2
            view.setText(text); // 3
        }
    
        // This is a custom binding adapter
        @BindingAdapter("app:hideIfZero")
        @JvmStatic fun hideIfZero(view: View, number: Int) {
            view.visibility = if (number == 0) View.GONE else View.Visible
        }
        
        // This is a multi-attributes binding adapter, which is called
        // whenever any of the bound variables of the attributes get changed.
        // It won't be used if any of the attributes are missing, which is 
        // determined at compile time. Refer BindingAdapter#requireAll for
        // more details about the default attribute values.
        // Generally, the requireAll parameter defines when the binding adapter is used:
        // When true, all elements must be present in the XML definition.
        // When false, the missing attributes will be null, false if booleans or 0 if primitives.
        @BindingAdapter(value = ["app:progressScaled", "android:max"], requireAll = true)
        @JvmStatic fun setProgress(progressBar: ProgressBar, likes: Int, max: Int) {
            progressBar.progress = (likes * max / 5).coerceAtMost(max)
        }
    

    Triggers of the binding adapter

    <ViewGroup>
        <TextView>
            android:text="@{vm.name}"
        </TextView>
        
        <ProgressBar>
            app:hideIfZero="@{vm.likes}"
            app:progressScaled="@{vm.likes}"
            android:max="@{100}"  // 5
        </ProgressBar>
    </ViewGroup>
    
    • 1: Annotates a Binding Adapter and the view attribute it applies to.
    • 2: Specifies the binding view and applicable type of value to the attribute.
    • 3: Implements how the value is applied to change the view attribute.
    • 4: In Kotlin, static methods can be created by adding functions to the top
      level of a Kotlin file or as extension functions on the class.
    • 5: Use a literal integer for a binding expression, otherwise, the DB won't find the defined adapter
  5. What's Binding Class

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,802评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,109评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,683评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,458评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,452评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,505评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,901评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,550评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,763评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,556评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,629评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,330评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,898评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,897评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,140评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,807评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,339评论 2 342

推荐阅读更多精彩内容