0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

leanbackライブラリにおけるViewBinding化の注意点

Posted at

leanbackライブラリにおけるViewBinding化の注意点

結論

class SampleVideoFragment : RowsSupportFragment() {
    private var _binding: FragmentSampleVideoBinding? = null
    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!
    private var _adapter: ArrayObjectAdapter = ArrayObjectAdapter(RowPresenterSelector())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        adapter = _adapter
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // これを追加
        super.onCreateView(inflater, container, savedInstanceState)
        // これを追加

        _binding = FragmentSampleVideoBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val data = ( 1..100).map {
            CustomCardRow(it)
        }
        _adapter.add(data)
        
        val gridView = CustomGridView()
        verticalGridView.addView(gridView)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

[参考]

なぜか

ViewBindingを行う場合、通常はsuper.onCreateView()を書かないことが多いです。

このverticalGridViewをSampleVideoFragmentからアクセスするとnullエラーになってしまいます。

RowsSupportFragmentの親クラスであるBaseRowSupportFragmentのonCreateView()にmVerticalGridViewと呼ばれるGridViewのメンバ変数があり、onCreateView()で初期化しています。

そのため、onCreateView()にて、親クラスのonCreateView()をコールする必要があります。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?