用活动组内的另一个片段替换片段

Lio*_*art 131 java android android-fragments

我在组活动中有一个片段,我想用另一个片段替换它:

FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
SectionDescriptionFragment bdf = new SectionDescriptionFragment();
ft.replace(R.id.book_description_fragment, bdf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
Run Code Online (Sandbox Code Playgroud)

它在没有使用活动组的情况下作为单独的项目完成时工作正常,因为控件进入getview()内部,每个东西都可以在log cat中正常工作,但是没有视图可见,甚至没有出现任何异常,我希望书籍详细信息片段为由部分细节片段替换.

书籍详细信息片段的Xml具有id book_description_fragment,而用于部分描述片段的xml具有id section_description_fragment.

上面的代码在项目的onClick方法中,我希望当用户点击水平滚动视图中的项目时,片段会发生变化.

Sub*_*ian 246

以XML格式编码的片段无法替换.如果你需要用另一个片段替换片段,你应该首先动态添加它们.

注意:R.id.fragment_container是您将片段带到的活动中所选择的布局或容器.

// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getSupportFragmentManager().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();
Run Code Online (Sandbox Code Playgroud)

  • 在这种情况下,R.id.fragment_container是什么? (7认同)
  • @Guy,它可以是您希望加载片段的任何布局. (4认同)
  • @Ahmed原因在于,通过体系结构,系统将每个<fragment>标签替换为相应片段"onCreateView()"提供的视图(组).因此,正如您可以假设的那样,对片段的任何引用实际上都在视图级别丢失.因此,您基本上无法替换片段,而是可以手动删除容器中现在存在的视图,并在需要时将片段放在那里. (3认同)

San*_*ana 35

请看这个问题

您只能替换" 动态添加的片段 ".

因此,如果要添加动态片段,请参阅示例.


Hug*_*sse 8

我已经用完美的方法来管理片段 替换生命周期.

它只用一个新片段替换当前片段,如果它不相同并且它不在backstack中(在这种情况下它将弹出它).

它包含几个选项,就好像您希望将片段保存在backstack中一样.

=> 见这里的要点

使用此活动和单个活动,您可能希望将其添加到您的活动中:

@Override
public void onBackPressed() {
    int fragments = getSupportFragmentManager().getBackStackEntryCount();
    if (fragments == 1) {
            finish();
            return;
    }

    super.onBackPressed();
}
Run Code Online (Sandbox Code Playgroud)


Sac*_*har 8

在android.support.v4中使用以下代码

FragmentTransaction ft1 = getFragmentManager().beginTransaction();
WebViewFragment w1 = new WebViewFragment();
w1.init(linkData.getLink());
ft1.addToBackStack(linkData.getName());
ft1.replace(R.id.listFragment, w1);
ft1.commit();
Run Code Online (Sandbox Code Playgroud)