Android Data Binding Library vs Kotlin Android Extensions

后端 未结 3 1595
故里飘歌
故里飘歌 2021-01-31 14:37

I\'m reading about how the MVVM architecture works and how to use Android Data Binding Library help.

In a very general way I understand that Android Data Binding creates

3条回答
  •  清酒与你
    2021-01-31 14:56

    I strongly disagree with the points mentioned above. maybe because I hate writing logic in XML. so both comments mention the use of tags not found in Kotlin Android Extensions (KTX). with kotlin and KTX you can do better than data tag.

    let's say we have

    data class Person(val name:String, 
                       val phone:String,
                       val isMale:Boolean,
                       val isMarried:Boolean)
    

    in the activity or fragment, we can do

    fun updateView(data:Person){
        with(data){
    
         nameTextField.text = if(isMale){
                                "Mr. $name" 
                              } else {
                                 if(isMarried){
                                  "Mrs. $name"
                                 }else{
                                  "Miss $name"
                                 }
                              }
         phoneTextField.text = phone
        }
     }
    

    in data-binding, you have to do

    android:text='@{person.isMale ? "Mr."+user.name: ((user.isMarried ? "Mrs. " : "Miss. ") + user.name)}'

    KTX code is way cleaner than what you have to do with data binding to achieve the same result. when you need conditions to set values to view data binding gets ugly. so for me, Kotlin Android Extensions work better. I like my code clean. you can still use both the decision is yours to make.

提交回复
热议问题