Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android actionbar items remain when popping fragment

I'm using the support actionbar. I'm also using fragments. Typically, I change the fragment using navigation drawer and everything works fine. Each fragment is able to make changes to the action bar items. When I change to a new fragment, the changes (new buttons) are removed.

Here's my problem. In one instance, I replace the fragment and add the existing fragment to the back stack. When I go back to the previous fragment, the actionbar still has the items from the previous fragment.

Example: 1) Fragment 1 loads fragment 2 and places fragment 1 on the back stack 2) Fragment 2 places several new buttons in the actionbar 3) Fragment 2 exits and now I see the actionbar items from fragment 1 & 2

I do the same basic thing with 2 other fragments in a different location and don't have the same problem. The only difference I can figure out between the two implementations is the way the 2nd fragments interact with the actionbar.

In the working case, fragment 2 load items inflating a menu in onCreateMenuOptions. This works well.

In the NOT working case, fragment 2 does NOT inflate a menu but uses a custom view:

         // Set action bar custom view and display options.
    MINMainActivity.getSharedInstance().getSupportActionBar().setCustomView(R.layout.custom_action_bar_viewer);
    MINMainActivity.getSharedInstance().getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_USE_LOGO);
    MINMainActivity.getSharedInstance().getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.action_bar_bg));

This is the only difference I can find. Am I missing something? (Obviously) But the question is what???

The code used to load the fragment 2 from fragment 1 is:

 MINMainActivity.getSharedInstance().mDrawerToggle.setDrawerIndicatorEnabled(false);

                        // Load the PDF fragment
                        MINPDFTronFragment fragment = new MINPDFTronFragment();
                        fragment.albumItem = albumItem;
                        getFragmentManager().beginTransaction()
                                .replace(R.id.content_frame, fragment)
                                .addToBackStack(null)
                                .commit();

The onCreate code used for fragment 2 is:

     // ***************************************************************************************************
//
//  onCreate
//
// ***************************************************************************************************
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    //MINMainActivity.getSharedInstance().supportRequestWindowFeature(WindowCompat.FEATURE_ACTION_BAR_OVERLAY);
    setRetainInstance(true);
    setHasOptionsMenu(true);
    getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
}

NEW EDITS:

These are the two methods that are doing the work on the action bar. The first section here is the code for Fragment 1. Fragment 1 is the fragment that launches Fragment 2 and places itself on the backstack:

     // ***************************************************************************************************
//
//  onCreateOptionsMenu
//
// ***************************************************************************************************
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
    mMenu = menu;

    // Inflate GridView menu
    inflater.inflate(R.menu.gridview_combined_menu, menu);

    // Gridview share menu
    MenuItem shareMenuItem = menu.findItem(R.id.MenuItemShare);
    mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareMenuItem);
    setGridViewShareIntent(null); // TODO is this needed?

    super.onCreateOptionsMenu(menu, inflater);
}


// ***************************************************************************************************
//
//  onPrepareOptionsMenu
//
// ***************************************************************************************************
@Override
public void onPrepareOptionsMenu(Menu menu)
{
    setOptionMenuItems();
    super.onPrepareOptionsMenu(menu);
}

Here are the same methods in Fragment 2 (the fragment launched by Fragment 1:

     // ***************************************************************************************************
//
//  onCreateOptionsMenu
//
// ***************************************************************************************************
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
    mMenu = menu;
    super.onCreateOptionsMenu(menu, inflater);
}


// ***************************************************************************************************
//
//  onPrepareOptionsMenu
//
// ***************************************************************************************************
@Override
public void onPrepareOptionsMenu(Menu menu)
{
    MINMainActivity MINMainActivity = (MINMainActivity) getActivity();
    boolean drawerIsOpen = MINMainActivity.mDrawerLayout.isDrawerOpen(MINMainActivity.mDrawerList);

    if(drawerIsOpen)
    {
    }

    else
    {
        }
    }
    super.onPrepareOptionsMenu(menu);
}

As you can see, Fragment 2 isn't making mods in those methods. Below is the code in Fragment 2 that manipulates the actionbar:

     // ***************************************************************************************************
//
//  onCreateView
//
// ***************************************************************************************************
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    initViewerLayout(inflater, container, savedInstanceState);
 }
     // ***************************************************************************************************
//
//  initViewerLayout
//
// ***************************************************************************************************
private void initViewerLayout(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    // Initialize the library
    try
    {
        PDFNet.initialize(MINMainActivity.getSharedInstance(), R.raw.pdfnet);
    }
    catch (PDFNetException e)
    {
        // Do something...
        e.printStackTrace();
    }

    // Inflate the view and get a reference to PDFViewCtrl
    pageView = inflater.inflate(R.layout.pdf_viewer, container, false);

    // Set action bar custom view and display options.
    MINMainActivity.getSharedInstance().getSupportActionBar().setCustomView(R.layout.custom_action_bar_viewer);
    MINMainActivity.getSharedInstance().getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_USE_LOGO);
    MINMainActivity.getSharedInstance().getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.action_bar_bg));

    // Initialize action bar buttons (we are using a custom view, so we
    // need to set click listeners for each item.
    mButtonViewMode = (ImageButton) MINMainActivity.getSharedInstance().getSupportActionBar().getCustomView().findViewById(R.id.ab_action_viewmode);
    mButtonViewMode.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ViewModePickerDialogFragment dialog = new ViewModePickerDialogFragment();
            dialog.mListener = MINPDFTronFragment.this;
            dialog.show(MINMainActivity.getSharedInstance().getSupportFragmentManager(), "view_mode_picker");
            stopHideToolbarsTimer();
        }
    });
    updateButtonViewModeIcon();

    mButtonOutline = (ImageButton) MINMainActivity.getSharedInstance().getSupportActionBar().getCustomView().findViewById(R.id.ab_action_outline);
    mButtonOutline.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentManager fragmentManager = MINMainActivity.getSharedInstance().getSupportFragmentManager();
            // Creates the dialog in full screen mode
            mBookmarksDialog = new BookmarksDialogFragment(mPdfViewCtrl, mBookmarkDialogCurrentTab);
            mBookmarksDialog.setBookmarksDialogFragmentListener(MINPDFTronFragment.this);
            mBookmarksDialog.mOutlineDialogFragmentListener = MINPDFTronFragment.this;
            mBookmarksDialog.mAnnotationDialogFragmentListener = MINPDFTronFragment.this;
            mBookmarksDialog.setStyle(DialogFragment.STYLE_NO_TITLE, android.support.v7.appcompat.R.style.Theme_AppCompat_Light);
            mBookmarksDialog.show(fragmentManager, "bookmarks_dialog");

            stopHideToolbarsTimer();

            // Example of how to show the OutlineDialogFragment as a dialog
            //OutlineDialogFragment outlineDialogFragment = new OutlineDialogFragment(mPdfViewCtrl);
            //outlineDialogFragment.setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Light);
            //outlineDialogFragment.show(fragmentManager, "outline_dialog");

            // Example of how to show the AnnotationDialogFragment as a dialog
            //AnnotationDialogFragment annotDialog = new AnnotationDialogFragment(mPdfViewCtrl);
            //annotDialog.setStyle(DialogFragment.STYLE_NO_TITLE, android.support.v7.appcompat.R.style.Theme_Base_AppCompat_Light);
            //annotDialog.show(fragmentManager, "annotation_dialog");
        }
    });

    mSearchView = (SearchView) MINMainActivity.getSharedInstance().getSupportActionBar().getCustomView().findViewById(R.id.ab_action_search);
    mSearchView.setFocusable(false);
    mSearchView.setFocusableInTouchMode(false);
    // Let's get the internal button of the search view widget to change some properties.
    ImageView searchButton = (ImageView) mSearchView.findViewById(android.support.v7.appcompat.R.id.search_button);
    searchButton.setBackgroundDrawable(mSearchView.getContext().getResources().getDrawable(R.drawable.controls_annotation_toolbar_tool_bg));
    searchButton.setImageDrawable(mSearchView.getContext().getResources().getDrawable(R.drawable.ic_action_search));
    mSearchView.setOnQueryTextListener(this);
    mSearchView.setIconifiedByDefault(true);
    mSearchView.setOnSearchClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            SearchView searchView = (SearchView) view;
            if (searchView.isIconfiedByDefault() && !searchView.isIconified()) {
                AnalyticsHandler.getInstance().sendEvent("[Viewer] Find Text clicked");

                // Search has expanded
                startSearchMode();
            }
        }
    });
    mSearchView.setOnCloseListener(new SearchView.OnCloseListener() {
        @Override
        public boolean onClose() {
            exitSearchMode();
            return false;
        }
    });

    mButtonAnnotToolbar = (ImageButton) MINMainActivity.getSharedInstance().getSupportActionBar().getCustomView().findViewById(R.id.ab_action_tools);
    mButtonAnnotToolbar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mAnnotationToolbar = new AnnotationToolbar(MINApplication.getAppContext(), pageView, mToolManager);
            mAnnotationToolbar.setButtonStayDown(SettingsManager.getContinuousAnnotationEdit(MINApplication.getAppContext()));

            if (SettingsManager.getContinuousAnnotationEdit(MINApplication.getAppContext())) {
                AnalyticsHandler.getInstance().sendEvent("[General] Continuous Annotation Edit enabled");
            }

            mAnnotationToolbar.show();

            AnalyticsHandler.getInstance().sendEvent("[Annotation Toolbar] Annotation Toolbar opened");
        }
    });

    mButtonShare = (ImageButton) MINMainActivity.getSharedInstance().getSupportActionBar().getCustomView().findViewById(R.id.ab_action_share);
    mButtonShare.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            if (MiscUtils.isKitKat()) {
                // If KitKat or higher, we show the Share/Print option
                SharePickerDialogFragment dialog = new SharePickerDialogFragment();
                dialog.mListener = MINPDFTronFragment.this;
                dialog.show(MINMainActivity.getSharedInstance().getSupportFragmentManager(), "share_mode_picker");
            } else {
                MiscUtils.sharePdfFile(MINApplication.getAppContext(), albumItem);
                AnalyticsHandler.getInstance().sendEvent("[Viewer] Share clicked");
            }
        }
    });

    // Search prev/next buttons.
    mButtonSearchNext = (ImageButton) pageView.findViewById(R.id.floating_button_next);
    mButtonSearchNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mSearchUp = false;
            findText();
        }
    });
    mButtonSearchPrev = (ImageButton) pageView.findViewById(R.id.floating_button_prev);
    mButtonSearchPrev.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mSearchUp = true;
            findText();
        }
    });

    // PDFViewCtrl settings
    mPdfViewCtrl = (CompleteReaderPDFViewCtrl) pageView.findViewById(R.id.pdfviewctrl);
    mPdfViewCtrl.setUrlExtraction(true);
    mPdfViewCtrl.setupThumbnails(true, true, true, 0, 50 * 1024 * 1024, 0.1);
    mPdfViewCtrl.setPageViewMode(PDFViewCtrl.PAGE_VIEW_FIT_PAGE);
    mPdfViewCtrl.setPageRefViewMode(PDFViewCtrl.PAGE_VIEW_FIT_PAGE);
    mPdfViewCtrl.setHighlightFields(true);
    mPdfViewCtrl.setZoomLimits(PDFViewCtrl.ZOOM_LIMIT_RELATIVE, 1.0, 20.0);
    updateViewMode();

    mSeekBar = (ThumbnailSlider) pageView.findViewById(R.id.thumbseekbar);
    // We pass a reference of the PDFViewCtrl to the slider so it can
    // interact with it (know number of pages, change pages, get thumbnails...
    // At this point no doc is set and the slider has no enough data
    // to initialize itself. When a doc is set we need to reset its data.
    mSeekBar.setPDFViewCtrl(mPdfViewCtrl);

    mPageNumberIndicator = (TextView) pageView.findViewById(R.id.page_number_indicator_current_page);

    mSearchProgressDialog = new ProgressDialog(getActivity());
    mSearchProgressDialog.setMessage(getResources().getString(R.string.search_in_progress));
    mSearchProgressDialog.setIndeterminate(true);
    mSearchProgressDialog.setCancelable(true);
    mSearchProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            mPdfViewCtrl.cancelFindText();
        }
    });

    mDownloadDocumentDialog = new ProgressDialog(getActivity());
    mDownloadDocumentDialog.setMessage(getResources().getString(R.string.download_in_progress_message));
    mDownloadDocumentDialog.setIndeterminate(true);
    mDownloadDocumentDialog.setCancelable(true);
    mDownloadDocumentDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            Toast.makeText(MINApplication.getAppContext(), R.string.download_cancelled_message, Toast.LENGTH_SHORT).show();
            //TODO finish();
        }
    });
}
like image 918
JustLearningAgain Avatar asked Jul 19 '14 03:07

JustLearningAgain


1 Answers

Try to call invalidateOptionsMenu() in onResume of your 1 fragment.

EDIT:

If custom actionbar was set in fragment 2, you'll need to disable it in your first fragment (for example, in onResume()):

MINMainActivity.getSharedInstance().getSupportActionBar().setDisplayOptions(Act‌​ionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_USE_LOGO);
like image 152
Dmide Avatar answered Nov 15 '22 19:11

Dmide