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>(
val responseTextView = findViewById<TextView>(
val bottomAppBar = findViewById<BottomAppBar>(
val fab = findViewById<FloatingActionButton>(
val productRecyclerView = findViewById<RecyclerView>(
val filterButton = findViewById<Button>(
val sortButton = findViewById<Button>(

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.


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.

Popular posts from this blog

How to Read Metadata from AndriodManifest File

Add Spacing to Recycler View Linear Layout Manager Using Item Decoration

Translucent and Transparent Background for Activity

Add Options Menu to Activity and Fragment

Create Assets Folder, Add Files and Read Data From It