View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module.
- Add this in to app module build.gradle in android under buildFeatures:
1 2 3 4 5 6 |
android{ ... buildFeatures { viewBinding = true } } |
- Create layout file – activity_main.xml:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activityMainLayout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello world" android:textSize="20sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> |
- In the MainActivity we need to declare this layout root element as class:
1 |
private ActivityMainBinding binding; |
- note: the class name for this binding to work needs to have the layout file name and word binding together with camel case.
In our case activity_main + binding = ActivityMainBinding class name.
and to set in in onCreate():
1 2 3 4 5 6 |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); } |
- Actual binding of the view declared in the activity_main.xml:
1 |
binding.textLabel.setText("Hello View Binding"); |
Why View Binding over natieve findViewById, ButterKnife library (apart that is now deprecated), Kotlin Synthetic, Data Binding:
Documentation:
https://developer.android.com/topic/libraries/view-binding 1
Part of Jetpack for Android:
https://developer.android.com/jetpack