Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

view binding

// for Kotlin
// IMPORTANT: DO NOT use <layout> tag in xml as for databinding
// This is meant for view binding only (assuming you don't need to bind data)
// viewbinding replaces findViewById()

// in the module-level build.gradle file add this
android {
    buildFeatures {
        viewBinding = true
    }
}

// in MainActivity

import com.example.appname.databinding.ActivityMainBinding // <----

private lateinit var binding: ActivityMainBinding // <----

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    
    binding = ActivityMainBinding.inflate(layoutInflater) // <----
    val view = binding.root // <----
    setContentView(view) // <----
    
    // now you are ready to use the binding instance
    // when binding, use camelCase of the view id (e.g. test_button)
    binding.testButton.setOnClickListener { doWhatever() }
}
Source by developer.android.com #
 
PREVIOUS NEXT
Tagged: #view #binding
ADD COMMENT
Topic
Name
5+3 =