【问题标题】:Navigation drawer - top fragment导航抽屉 - 顶部片段
【发布时间】:2014-09-08 23:29:52
【问题描述】:

我有导航抽屉和一系列片段。在层次结构的最后一个片段上,我在操作栏上有 UP 按钮。单击此按钮时,将调用根活动的 onOptionsItemSelected(MenuItem item) ,我可以在其中找到在以下谓词中单击了哪个按钮:

    else if ( item.getItemId() ==  android.R.id.home )
    {
        System.out.println("android.R.id.home\n\n");
       // super.onBackPressed();
      // getFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).commit();
        return true;
    }

如何删除当前片段?我已经阅读了有关后堆栈的信息,但是这种方法需要使用键将片段保存在堆栈中。我怎样才能避免这个过程?

【问题讨论】:

    标签: java android android-fragments navigation-drawer


    【解决方案1】:

    当我第一次开始使用它们时,我曾遇到过片段彼此重叠的问题。我使用此代码添加片段:

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction transaction =fragmentManager.beginTransaction();
    Fragment fragment = new CustomFragment(); // your fragment to add
    transaction.replace(R.id.content_frame, fragment,CustomFragment.TAG); // a string in case you need to check with fragment is currently visible.
    transaction.addToBackStack(null);
    transaction.commit();
    

    这将确保当您按下返回按钮时,当前的按钮会消失,而之前的按钮会显示。

    希望它对你有用。

    【讨论】:

      【解决方案2】:

      实际上,您可以直接弹出后台堆栈,无需通过键/标签进行跟踪:FragmentManager.popBackStack()。将你的fragment添加到back stack时只要使用null,系统会自动为其选择一个tag。

      【讨论】:

      • 是的,我已经找到了。不幸的是,片段保留在屏幕上,但 alpha 较小 - 我可以通过它看到以前的片段
      • 听起来你还有其他事情要做。如果您添加了一个片段(或替换)并告诉事务将其添加到后台堆栈,弹出将删除它并恢复之前在容器中的内容。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-16
      • 2016-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多