How to hide action bar for fragment?

前端 未结 9 1185
挽巷
挽巷 2021-01-31 08:17

How can I hide action bar for certain fragment? I have searched for the answer at stackoverflow, but I have only found a solution, which involves disabling action bar for main a

9条回答
  •  别那么骄傲
    2021-01-31 08:51

    As it was already mentioned, actionbar may be hidden by (requireActivity() as AppCompatActivity).supportActionBar?.hide() call. If you want to show it in some of your fragments and to hide it in some other fragments, it may be convenient to apply default (for your case) visibility in onViewCreated of your Base fragment:

    abstract class BaseFragment : Fragment() {
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            (requireActivity() as AppCompatActivity).supportActionBar?.show()
        }
    }
    

    and to hide it in particular fragments:

    class HiddenActionBarFragment : BaseFragment() {
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            (requireActivity() as AppCompatActivity).supportActionBar?.hide()
        }
    }
    

    This solution is more flexible than using onStart - onStop for visibility change because during the transition onStart of a different fragment will be called earlier than onStop of the current fragment. So the next fragment won't be able to 'override' actionar visibility applied in onStop of the current fragment.

提交回复
热议问题