[Android 앱 개발 숙련] 1. 뷰 바인딩

0
post-thumbnail

[Android 앱 개발 숙련] 1. 뷰 바인딩

📌참고자료: View Binding | Android Developers

  • 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
// This property is only valid between onCreateView and
// onDestroyView.
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
profile
Be able to be vulnerable, in search of truth

0개의 댓글