View binding is a feature in Android that allows you to access views in your layout XML file directly from your code, without the need to call findViewById
for each view. View binding generates a class for each layout file in your project, which provides direct access to the views in the layout.
To use view binding in a fragment in Android, you will need to do the following:
build.gradle
file:android { viewBinding { enabled = true } }
onCreateView
method, as you would normally do.@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_my, container, false); }
bind
method on the ViewDataBinding
class and assign the result to a variable. Then, you can use this variable to access the views in your layout directly.@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment FragmentMyBinding