Issue
I am using view binding with Java and have the following activity_main XML file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<GridView
android:id="@+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
The official example in the docs shows that views can be accessed through a camel-case getter, like this:
binding.getName().setText(viewModel.getName());
According to the example in the docs then, I should be able to access the GridView from the binding like this
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
GridView grid = binding.getGridView();
}
However, no getGridView
method exists on my binding class. How do I access the view?
Solution
Unfortunately, the view binding documentation code examples with Java are out of date. Instead of generating a camel-case getter function now the generated binding class has public (and final) fields so you can access them directly, like this:
GridView grid = binding.gridView;
In the future, if you type binding.
and let the IDE (i.e. Android Studio) show a suggestion of what to type (usually it shows up in a popup/dropdown view) it can help find the right method even when the documentation is wrong.
Answered By - Tyler V
Answer Checked By - Willingham (JavaFixing Volunteer)