Steven Fisher
Steven Fisher

Reputation: 44886

Adding top actions to bottom navigation activity app?

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. App template

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

Answers (1)

Steven Fisher
Steven Fisher

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

  1. Create a new menu resource in res/menu. Yes, another one if you already have one for the bottom menu. (This is what I couldn't find documented anywhere: you don't add to your existing menu, you create a new one.) I called mine account_menu.
  2. Call setHasOptionsMenu(true) in your Fragment's onCreate()
  3. Implement onCreateOptionsMenu in your Fragment.
  4. Handle clicks on your menu items 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

Related Questions