Material Components Android: BottomAppBar — Part II

In the previous post we defined the implementation and use of this component. In this post we’ll specify some features about its behavior and the reaction to actions from other components.

Actions

Bottom app bars can contain actions that apply to the context of the current screen.

In order to add these actions we must define our menu XML file and specify which items will be present.

To create this menu, we inflate the menu in the onCreateOptionsMenu() function.

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(bottomAppBar)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.bottomappbar_menu_primary, menu)
return true
}

To specify the action for each item, we’ll define these actions in the onOptionsItemSelected() function.

override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when(item!!.itemId) {
android.R.id.home -> toast("Menu clicked!")
R.id.search -> toast("Search clicked!")
}
return true
}

Behavior

Layout

One of the actions that usually our app does is the change between fragments and views. The position of the FAB can be adapted to the need of the current view.

switchScreenButton.setOnClickListener {
fab.hide(object : FloatingActionButton.OnVisibilityChangedListener(){
override fun onShown(fab: FloatingActionButton?) {
super.onShown(fab)
}

override fun onHidden(fab: FloatingActionButton?) {
super.onHidden(fab)
textView.text = "Secondary screen"
bottomAppBar.fabAlignmentMode = BottomAppBar.FAB_ALIGNMENT_MODE_END
bottomAppBar.replaceMenu(R.menu.bottomappbar_secondary_menu)
fab?.setImageDrawable(getDrawable(R.drawable.ic_twotone_check_24px))
fab?.show()
}
})
bottomAppBar.navigationIcon = null
}

When the switch screen button is clicked, we modify the visibility of the FAB in order to represent the change between views as well as the menu is modified.

Scrolling

Upon scroll, the bottom app bar can appear or disappear. Scrolling downward hides the bottom app bar. If a FAB is present, it detaches from the bar and remains on screen. Scrolling upward reveals the bottom app bar, and reattaches to a FAB if one is present.

In order to get this behavior we must to declare as ‘true’ the value of the ‘hideOnScroll’ attribute of our component.

Code