2
2

More than 1 year has passed since last update.

ViewBindingをonViewCreated以外でも使う時とonViewCreatedでしか使わない時

Posted at

使い分けが必要

ViewBindingonViewCreated以外でも使う時と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を宣言してしまいます。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2