使い分けが必要
ViewBinding
をonViewCreated
以外でも使う時とonViewCreated
でしか使わない時とでは書き方が異なる。できるだけ、変数のスコープが狭くしたいという意図がある。また、今回はFragmentのonViewCreated
においての話であるが、ActivityのonCreate
に関しても同様である。
onViewCreated以外でも使う時
private var _binding: FragmentHomeAllBinding? = null
private val binding
get() = _binding!!
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
_binding = FragmentHomeAllBinding.bind(view)
binding.allRecyclerView.adapter = homeAllAdapter
viewModel.renderData.observe(viewLifecycleOwner) {
homeAllAdapter.update(it, viewModel)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
onViewCreatedだけで使う時
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = FragmentHomeShoesBinding.bind(view)
}
onViewCreatedだけで使う場合は、上記のように、onViewCreated
内でbidingを宣言してしまいます。