— Android, Jetpack, View Binding — 1 min read
Jetpack View Binding is a relatively new feature in Android that allows developers to easily access views in their code, without the need for the traditional findViewById method. This can make code cleaner, more efficient, and easier to read.
To implement Jetpack View Binding in your Android project, follow these steps:
Make sure you have Android Studio 4.2 or higher, as View Binding is only available in the latest version of the IDE.
In your build.gradle file, add the viewBinding option to the buildFeatures section:
1android {2 buildFeatures {3 viewBinding = true4 }5}
1<TextView2 android:id="@+id/hello_world"3 android:layout_width="wrap_content"4 android:layout_height="wrap_content"5 android:text="Hello, World!" />
1// In MainActivity.kt2
3private lateinit var binding: MainActivityBinding4
5override fun onCreate(savedInstanceState: Bundle?) {6 super.onCreate(savedInstanceState)7 binding = MainActivityBinding.inflate(layoutInflater)8 setContentView(binding.root)9}
1// In MainActivity.kt2
3binding.helloWorld.text = "Hello, Jetpack View Binding!"
That's it! You have successfully implemented Jetpack View Binding in your Android project. This new feature makes it easier to access views in your code, and can make your code cleaner, more efficient, and easier to read.