- build.grable에 viewBinding 요소 추가
android{
...
buildFeatures{
viewBinding true
}
}
- a binding class is generated for each XML layout file
- binding class는 루트 뷰와 ID가 있는 모든 뷰에 대한 reference를 포함한다
- binding class의 이름: XML 파일 이름의 Pascal case + "Binding"
- Activity에서 뷰 바인딩 사용하기
(1) inflate(): creates an instance of the binding class
(2) getRoot(): get reference to root view
(3) setContentVieW()의 매개변수로 root view reference 넘기기
private lateinit var binding: ResultProfileBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ResultProfileBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
}
- Fragment에서 뷰 바인딩 사용하기
(1) inflate(): creates an instance of the binding class
(2) getRoot(): get reference to root view
(3) onCreateView()의 반환값으로 root view reference 넘기기
private var _binding: ResultProfileBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = ResultProfileBinding.inflate(inflater, container, false)
val view = binding.root
return view
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
- findViewBuId와의 차이점
- Null safety: no risk of a null pointer exception due to an invalid view ID
- Type safety: no risk of a class cast exception