ViewBinding vs Kotlin Android Extensions with synthetic views

后端 未结 5 1276
予麋鹿
予麋鹿 2020-12-13 03:33

How does the new ViewBinding compare with the Kotlin Android Extensions with synthetic views bindings?

Apart form the NullSafety and TypeSafety provided by new ViewB

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 03:55

    ViewBinding solved the biggest problem of kotlinx.android.synthetic. In synthetic binding if you set your content view to a layout, then type an id that only exists in a different layout, the IDE lets you autocomplete and add the new import statement. Unless the developer specifically checks to make sure their import statements only import the correct views, there is no safe way to verify that this won’t cause a runtime issue. But in ViewBinding you should use your layout binding object to access its views so you never invoke to a view in a different layout and if you want to do this you will get a compile error not a runtime error. Here is an example.

    We create two layouts called activity_main and activity_other like so :

    activity_main.xml

    
    
        
    
    
    

    activity_other.xml

    
    
        
    
    
    

    Now if you write your activity like this:

    import android.os.Bundle
    import android.support.v7.app.AppCompatActivity
    import kotlinx.android.synthetic.main.activity_other.*
    
    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            //Application will crash because "message_other" doesn't exist in "activity_main"
            message_other.text = "Hello!"
        }
    }
    

    your code will compile without any error but your application will crash at runtime. Because the view with message_other id doesn't exist in activity_main and the compiler didn't check this. But if you use ViewBinding like so:

    class MainActivity : AppCompatActivity() {
        private lateinit var binding: ActivityMainBinding
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            binding = ActivityMainBinding.inflate(layoutInflater)
            setContentView(binding.root)
            //This code will never compile and the IDE shows you an error
            binding.message_other.text = "Hello!"
        }
    }
    

    your code will never compile and Android Studio shows you an error in the last line.

提交回复
热议问题