【问题标题】:Check fragment is presented in framelayout or not in android?检查片段是否出现在框架布局中或不在android中?
【发布时间】:2013-08-26 13:24:42
【问题描述】:

嗨朋友们,我在movies.xml中有两个框架布局,即containerdetail_screen。在容器中将添加包含listview的movies.xml,并且在 detail_screen 中将有一个名为 movie_details.xml 的可扩展列表视图。现在想以编程方式检查 detail_screen 是否已经呈现片段。如果呈现只是想删除该片段。我通过以下方式完成了它的工作正常。

    if (getSupportFragmentManager().findFragmentByTag("MyFragment") != null) {
        getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().findFragmentByTag("MyFragment")).commit();
}

但是有没有其他方法可以通过编程方式在 android 的框架布局中查找片段是否存在。在此先感谢

【问题讨论】:

  • 不使用 findFragmentByTag()/Id
  • 您想知道片段是否存在,但没有对其或其容器的引用? getSupportFragmentManager().getFragments() 检索该管理器的片段列表。
  • @kmg 我想检查我的框架布局中是否已经存在片段只是想删除该片段添加新片段,否则将多次添加相同的片段
  • 如果您使用getSupportFragmentManager().beginTransaction().replace(),它将替换或添加 - 您不必担心删除现有片段
  • @sugan.s replace() 不适合您的情况?

标签: android fragment android-framelayout


【解决方案1】:

我创建的解决方案如下。即在向 details_screen 添加任何片段之前,只需检查是否已经存在片段,然后弹出它,然后添加新片段。

if (getSupportFragmentManager().findFragmentById(R.id.detail_screen) != null) {

        getSupportFragmentManager().popBackStack();

            } //to do add fragment

希望它会起作用。

【讨论】:

    【解决方案2】:

    必须使用findFragmentByTag()findFragmentById() 方法来找到它。如果返回的实例不为空,则片段存在。此外,您可以使用Fragment.isInLayout() 方法检查片段是否在布局中使用<fragment> 标签定义或以编程方式添加。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-04
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多