Fragment with viewBinding in android by Rekibur Uddin

In modern Android development, ViewBinding provides a type-safe way to interact with views in XML layouts. It significantly reduces the need for findViewById() and helps avoid null pointer exceptions.

When working with Fragments, integrating ViewBinding requires attention to the fragment lifecycle. 

Prerequisites:

android {
// Inside
buildFeatures {
viewBinding = true
}
//
}


1. Create Fragment

New>Fragment>Blank Fragment.

2. Fragment Implementation


class ExampleFragment : Fragment() {

// ViewBinding instance (nullable, scoped to Fragment lifecycle)
private var _binding: FragmentExampleBinding? = null
private val binding get() = _binding!!

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate using binding
_binding = FragmentExampleBinding.inflate(inflater, container, false)
return binding.root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Access views & Fun call

}

override fun onDestroyView() {
super.onDestroyView()
// Prevent memory leaks
_binding = null
}
}


Why Use _binding Instead of Direct binding

  • Fragments outlive their views. So if you keep a reference to the view after it's destroyed, it may cause memory leaks.

  • Hence, _binding is set to null in onDestroyView() to clean up the view reference properly.

Best Practices

  • Always access binding using get() only between onCreateView and onDestroyView.

  • Never use binding outside that window (e.g., in onAttach or onDestroy).

  • Avoid holding binding in a global scope.


Conclusion

Using ViewBinding in Fragments ensures cleaner, safer, and more maintainable code. By properly managing the binding lifecycle, especially with nullable _binding, you prevent crashes and memory leaks in your Android apps.












No comments:

Post a Comment