Use Kotlin Android Extensions to Replace findViewById

Kotlin Android Extensions is a great way to avoid writing findViewById in the activity or fragment.

Simply, add the kotlin-android-extensions plugin to the module level build.gradle file.

apply plugin: 'kotlin-android-extensions'

Only one step to enable the feature. Now, we can remove the manual initializations.

// Initialize the UI elements
val constraintLayout = findViewById<ConstraintLayout>(R.id.coordinatorLayout)
val responseTextView = findViewById<TextView>(R.id.responseTextView)
val bottomAppBar = findViewById<BottomAppBar>(R.id.bottomAppBar)
val fab = findViewById<FloatingActionButton>(R.id.fab)
val productRecyclerView = findViewById<RecyclerView>(R.id.productRecyclerView)
val filterButton = findViewById<Button>(R.id.filterButton)
val sortButton = findViewById<Button>(R.id.sortButton)

The compilers suggest us only one import to get all the synthetic properties available in the layout. If the above views are available in the activity_main layout then the following import is sufficient.

import kotlinx.android.synthetic.main.activity_main.*

If our Android project is not a pure Kotlin project and we want to remove findViewById function in both Kotlin and Java classes then implement View Binding rather than Android Extensions.