How to use ViewBinding in an Android app?

ViewBinding is a feature that allows you to more easily write code that interacts with views. With ViewBinding, you can access views directly without using findViewById(). This can lead to less boilerplate code and reduces the risk of null pointer exceptions. Below is a step-by-step guide on how to implement ViewBinding in your Android app.

Step 1: Enable ViewBinding

First, you need to enable ViewBinding in your build.gradle file. Add the following line inside the android block:

android { ... buildFeatures { viewBinding true } }

Step 2: Create a Layout XML File

Create a new layout XML file in the res/layout directory. For example, let's create activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, ViewBinding!" /> </LinearLayout>

Step 3: Access Views in Your Activity

In your Activity, you can now access the views directly using the binding object. Here's how to do it in MainActivity.java:

public class MainActivity extends AppCompatActivity { private ActivityMainBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); binding.textView.setText("Welcome to ViewBinding!"); } }

ViewBinding Android ViewBinding Android development Kotlin ViewBinding Java ViewBinding