7

嗨朋友们,我在movies.xml中有两个框架布局,即容器detail_screen。在容器中将添加包含listview的movies.xml,并且在detail_screen中将具有名为 movie_details.xml可扩展列表视图。现在想以编程方式检查detail_screen是否已经呈现片段或not.if 提出只是想删除该片段。我按照以下方式进行了操作,并且工作正常。

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

但是有没有其他方法可以通过编程方式在android的框架布局中找到片段是否存在。提前致谢

4

2 回答 2

13

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

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

        getSupportFragmentManager().popBackStack();

            } //to do add fragment

希望它会奏效。

于 2013-08-27T11:11:59.023 回答
8

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

于 2013-08-26T13:39:10.373 回答