弹出片段时,Android操作栏项仍保留 [英] Android actionbar items remain when popping fragment

查看:90
本文介绍了弹出片段时,Android操作栏项仍保留的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用支持操作栏.我也在使用片段.通常,我使用导航抽屉更改片段,并且一切正常.每个片段都可以更改操作栏项.当我更改为新片段时,更改(新按钮)将被删除.

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.

示例:1)片段1加载片段2并将片段1放在后堆栈上2)片段2在操作栏中放置了几个新按钮3)片段2退出,现在我看到了片段1&的动作栏项目.2

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.

在工作情况下,片段2加载使onCreateMenuOptions中的菜单膨胀的项目.效果很好.

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

在不工作"情况下,片段2不会使菜单膨胀,而是使用自定义视图:

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???

用于从片段1加载片段2的代码是:

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();

用于片段2的onCreate代码是:

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);
}

这是在操作栏上执行工作的两种方法.这里的第一部分是Fragment 1的代码.Fragment 1是启动Fragment 2并将其放置在后堆栈中的片段:

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);
}

以下是片段2中的相同方法(片段1启动的片段:

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);
}

如您所见,Fragment 2不在这些方法中制作mod.以下是片段2中操纵操​​作栏的代码:

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();
        }
    });
}

推荐答案

尝试调用 onResume 中的="noreferrer"> invalidateOptionsMenu().

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

如果在片段2中设置了自定义操作栏,则需要在第一个片段中将其禁用(例如,在 onResume()中):

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

这篇关于弹出片段时,Android操作栏项仍保留的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆