First, open your app/build.gradle
file
Inside the android{}
block of app/build.gradle
, add the following:
buildFeatures { viewBinding = true }
Sync project with gradle files.
In your activity or fragment, define the following class-wide property:
1 |
private lateinit var binding: <strong>FragmentorActivityNameBinding</strong> |
Replace the FragmentorActivityNameBinding
above with the appropriate binding class name. Tip: The binding class name is based on the XML file’s name. For example, if your XML file name is activity_main.xml
, the binding class name should be ActivityMainBinding
. Or, if your file name is fragment_main.xml
, the binding class name should be FragmentMainBinding
.
In your activity, the onCreate
function should look like this:
1 2 3 4 5 6 7 |
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(<em>layoutInflater</em>) val view = binding.<em>root </em>setContentView(view) } |
Otherwise, if using view binding in a fragment, your onCreateView
should look like this:
1 2 3 4 5 6 7 8 9 10 |
override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentMainBinding.inflate(inflater, container, false) binding.<em>lifecycleOwner </em>= <em>viewLifecycleOwner </em> binding.<em>viewModel </em>= mainViewModel return binding.<em>root </em>} |