Reputation: 44886
I want to add actions to the top bar of my application in some tabs.
I started with Bottom Navigation Activity template. Here's a screenshot of the template application running, with where I want the button circled.
In my app, the last tab is Account. I want to add a button to the right side of the application title bar, but only when Account is up. (Other fragments might have different buttons, but most won't have any.)
In my Account fragment's onCreateView
, I've tried accessing activity?.actionBar
but it's null. I've also tried adding a toolbar to the XML, but that just adds a second bar. And, of course, I looked through Add and handle actions, but the presence of two bars in my app made it hard for me to puzzle out what it was asking of me.
How do I add an item here? I'd prefer to do it in XML, but I'll do it programatically if I must.
Upvotes: 0
Views: 69
Reputation: 44886
As @ianhanniballake points out, there's some documentation specific to Fragments and App Bars: Working with the AppBar
I don't want to just drop the link here, so here's how I read it (and if I got anything wrong, please comment and I'll correct it):
account_menu
.setHasOptionsMenu(true)
in your Fragment's onCreate()
onCreateOptionsMenu
in your Fragment.The code you've added to your fragment will look something like this:
override fun onCreate(savedInstanceState: Bundle?) {
setHasOptionsMenu(true)
super.onCreate(savedInstanceState)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.account_menu, menu);
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_settings -> {
// navigate to settings screen
true
}
else -> super.onOptionsItemSelected(item)
}
}
Upvotes: 1