Android Fragment Access Activity

Sep 28, 2019
Show/Hide BottomNavigationView and Toolbar

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)    }}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.