1

I'm trying to implement a navigation drawer, and I've been following https://developer.android.com/training/implementing-navigation/nav-drawer#java step by step. The only difference is that I am implementing everything inside a fragment instead of an activity directly.

As required by the documentation, I created a Toolbar and implemented Home button inside the onCreateView:

Toolbar toolbar = rootView.findViewById(R.id.toolbar);
        ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
        ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_black_24dp);

The problem now is that when the home button is pressed, onOptionsItemSelected is not called at all. Following is how I have overridden my onOptionsItemSelected:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            //mDrawerLayout.openDrawer(GravityCompat.START);
            Timber.d("Home Button Pressed");
            mDrawerLayout.openDrawer(GravityCompat.START, true);
            return true;
    }
    return super.onOptionsItemSelected(item);
}

Can anyone tell what is wrong? The GitHub link for this project is shown below if you want to see the rest of my code. Thank you! https://github.com/chao-li/GameCodex

Chao Li
  • 391
  • 1
  • 2
  • 13
  • You need to call `setHasOptionsMenu(true)` in the `Fragment`. – Mike M. Aug 23 '18 at 10:13
  • Thank you, I didn't realize that method was required for fragments. Also, I didn't find the other Stack post that answered the same question, other questions I found were caused by other causes. So should I delete this post? – Chao Li Aug 23 '18 at 10:21
  • No problem. It's cool. I just have a little more experience searching the site. :-) It's up to you, if you want to delete. There's nothing wrong with duplicate questions. They serve as signposts to the relevant answers. Your question might just make it easier for someone in the future to find the answer, if they happen to be searching for terms and keywords that appear here. – Mike M. Aug 23 '18 at 10:25
  • Ok, I think I will just leave it here. Make it easier for others to search. Do you want to answer the question officially, so I can mark it as an accepted solution? – Chao Li Aug 23 '18 at 10:37
  • Can't post answers when it's closed. That's part of the reason for closing as a duplicate; to keep the answers in one spot. (I realize it didn't quite work for this one, what with the multiple duplicates already here, but that's the idea, anyway.) Thank you, though. I appreciate the offer. Glad you got it working. Cheers! – Mike M. Aug 23 '18 at 10:49

0 Answers0