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.
First, you need to enable ViewBinding in your build.gradle file. Add the following line inside the android block:
android {
...
buildFeatures {
viewBinding true
}
}
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>
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!");
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?