【问题标题】:How do I get the current Fragment and replace it with another fragment如何获取当前的 Fragment 并将其替换为另一个 Fragment
【发布时间】:2016-01-01 11:09:26
【问题描述】:

我正在开发导航抽屉,目前正在使用:

getSupportFragmentManager().beginTransaction().replace(R.id.mainfragment, f1).commit();

但是正如你所看到的,它总是用新的片段替换主片段。谢谢!

【问题讨论】:

  • 此方法将容器中的任何片段替换为 id mainfragment。如果要替换另一个,请选择其容器的 id。请记住,除了替换之外,您还有其他方法,例如 add,它允许您在同一个容器中重叠片段。

标签: android android-fragments


【解决方案1】:

您可以执行 beginTransaction().replace (container, newFragment, tag),其中 container 是 xml 文件中 ViewGroup 的 id。所以被替换的东西是容器中当前的任何片段。

【讨论】:

    【解决方案2】:

    在 XML 中硬编码的片段不能被替换。如果你需要用另一个片段替换一个片段,你应该首先动态添加它们。

    // Create new fragment and transaction
    Fragment newFragment = new ExampleFragment();
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    
    // Replace whatever is in the fragment_container view with this fragment,
    // and add the transaction to the back stack if needed
    transaction.replace(R.id.fragment_container, newFragment);
    transaction.addToBackStack(null);
    
    // Commit the transaction
    transaction.commit();
    

    因此您只能通过以下链接替换“动态添加的片段”:

    http://notionink.wikidot.com/rajeshbabu

    http://sapandiwakar.in/replacing-fragments/

    【讨论】:

    • 通过在 xml 中硬编码你的意思是为他们准备一个 xml 布局文件吗?如果是这样,我还能如何设置布局样式?
    • 是的,您不能替换布局文件中静态定义的片段。您只能替换通过 FragmentTransaction 动态添加的片段。
    【解决方案3】:
    final FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(getId(), new SearchVideoDownloadFragment(), "NewFragmentTag");
    ft.commit();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      相关资源
      最近更新 更多