Java use view binding in fragment

h‮/:sptt‬/www.lautturi.com
Java use view binding in fragment

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:

  1. Enable view binding in your project: View binding is disabled by default in Android. To enable it, you will need to add the following line to your build.gradle file:
android {
  viewBinding {
    enabled = true
  }
}
  1. Inflate the layout in your fragment: To use view binding in your fragment, you will first need to inflate the layout in your fragment's 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);
}
  1. Generate and use the view binding class: Once the layout is inflated, you can generate and use the view binding class for the layout. To do this, you will need to call the 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
Created Time:2017-10-17 22:51:24  Author:lautturi