onCreateOptionsMenu не вызывается, если supportActionBar имеет значение null перед фрагментом onCreate - PullRequest
0 голосов
/ 05 августа 2020

Если у меня есть одно действие с одним фрагментом, fragment1 , и я использую компонент навигации для перехода от fragment1 к fragment2 после установки supportActionBar на null в onDestroyView, onCreateOptionsMenu не вызывается, даже если setHasOptionsMenu(true) вызывается в onCreate.

fragment1.kt:

...
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        (requireActivity() as AppCompatActivity).setSupportActionBar(toolbar) //kotlin view extension to the Toolbar in fragment1.xml
        view.findViewById<Button>(R.id.without_toolbar_button).setOnClickListener {
            findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        (requireActivity() as AppCompatActivity).setSupportActionBar(null)
    }
...

fragment2.kt:

...
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        (requireActivity() as AppCompatActivity).setSupportActionBar(toolbar)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        Toast.makeText(requireActivity(), "onCreateOptionsMenu called!", Toast.LENGTH_SHORT).show() //this is never called if navigation occurs from fragment1 to this fragment.
        super.onCreateOptionsMenu(menu, inflater)
    }
...

fragment1. xml & fragment2. xml:

...
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" ... />
...

Тост никогда не вызывается. Полный демонстрационный проект, демонстрирующий это, можно найти и клонировать на github .

«У меня были проблемы с фрагментами, оставшимися в памяти. После добавления setSupportActionBar (null) фрагменты были собраны в мусор». См. этот ответ из ветки про утечки памяти.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...