简体   繁体   中英

Android - Switching between fragments; Menu Item problems

My application uses fragments, action bar, and a navigation drawer. When I switch between fragments my menu items become broken and no longer function. I have tried a variety of things that may fix the problem but to no avail.

In my Fragment onCreate I have setHasOptionsMenu(true); .

This is my onCreateOptionsMenu :

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    Log.d("Log", "Inflating Menu");
    menu.clear();
    inflater.inflate(R.menu.blank, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

This is my simple onOptionsItemSelected :

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.mySearch:
            Log.d("Log", "Implementing Search Method");
            search();
            return true;

        case R.id.action_settings:
            //do something
            return true;
    }
    return super.onOptionsItemSelected(item);
}

In each Fragment's menu I use menu.Clear(); to prevent a pile up of Menu Items while switching between Fragments. The menu runs the selected function just fine when the Fragment is selected for the first time, but after switching to another Fragment and back again Menu Item clicks do nothing.

Issue is your clearing the menu and doing inflate menu again.

Remove the line

     inflater.inflate(R.menu.blank, menu);

Instead you need to just clear the menu in onCreateOptionsMenu() of Fragment , so that the menu will not be shown for that speciifc fragment , and will show for other fragment.

Also you need to inflate the menu only in Activity onCreateOptionsMenu which is common to all the fragment

Also see my answer here. Action buttons are shown in all fragments

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM