从片段管理器中删除旧片段

kho*_*oub 61 android android-tabhost android-fragments

我正在尝试学习如何Fragment在android中使用s.当我在Android中调用fragmentnew时,我正试图删除旧的fragment.

Yas*_*tel 144

您需要找到现有Fragment的参考,并使用下面的代码删除该片段.您需要使用一个标签ex添加/提交片段."TAG_FRAGMENT".

Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
if(fragment != null)
    getSupportFragmentManager().beginTransaction().remove(fragment).commit();
Run Code Online (Sandbox Code Playgroud)

这就对了.


Lok*_*esh 19

如果要将片段替换为另一个片段,首先应该动态添加它们.以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
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();
Run Code Online (Sandbox Code Playgroud)

请参阅此文章:用活动组内的另一个片段替换片段

参考1:以编程方式替换片段


Ale*_*der 9

我有同样的问题来删除旧的碎片.我最终清除了包含片段的布局.

LinearLayout layout = (LinearLayout) a.findViewById(R.id.layoutDeviceList);
layout.removeAllViewsInLayout();
FragmentTransaction ft = getFragmentManager().beginTransaction();
...
Run Code Online (Sandbox Code Playgroud)

我不知道这是否会造成泄漏,但它对我有用.

  • 这只会从布局中删除片段的视图。片段本身仍然附加到片段管理器,不会停止、分离或销毁。 (4认同)

小智 8

我遇到过同样的问题。我想出了一个简单的解决方案。使用 fragment.replace而不是 fragment .add。替换片段与添加片段然后手动删除它做同样的事情。

getFragmentManager().beginTransaction().replace(fragment).commit();
Run Code Online (Sandbox Code Playgroud)

代替

getFragmentManager().beginTransaction().add(fragment).commit();
Run Code Online (Sandbox Code Playgroud)