Assuming you are using BottomNavigationView
to navigation between a few fragment, and you might show/hide Activity's BottomNavigationView
or Toolbar
in certain condiitons.
Solution 1: Direct access activity view
class HomeFragment : Fragment() { fun hideToolbar() { // access toolbar via Kotlin Android Extensions - ViewBinding activity?.toolbar?.apply { isVisible = false // via Android KTX } }}
Solution 2: Via ViewModel and LiveData Event
MainActivity
class MainActivity : AppCompatActivity() { private lateinit var viewModel: MainViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main) setSupportActionBar(toolbar) viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java) init() } fun init() { viewModel.showBottomNavigationEvent.observe(this, Observer { event -> event.getIfPending()?.let { show -> bottomNavView.isVisible = show } }) }}
class MainViewModel : ViewModel() { internal val showBottomNavigationEvent = MutableLiveData<Event<Boolean>>()}
NOTE: Refer to LiveData Event Wrapper.
HomeFragment
class HomeFragment : Fragment() { private lateinit var viewModel: HomeViewModel private lateinit var mainViewModel: MainViewModel override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java) mainViewModel = ViewModelProviders.of(activity!!).get(MainViewModel::class.java) } fun hideBottomNavigation() { mainViewModel.showBottomNavigationEvent.value = Event(false) }}