片段替换现有片段 [英] Fragment Replacing Existing Fragment
问题描述
我有MainActivity,它包含ListFragment和framelayout,我能够在单击项目时更改列表上的片段.
在单击 Fragment1
, Fragment2
时,我有一个问题用新的 Fragment2
替换现有的 Fragment1
.code>应该替换 Fragment1
,并在左侧具有相同的ListFragment,并且应该正确处理后退按钮,这意味着当我在 Fragment2
中并按后退按钮时应该显示相同的ListFragment和Fragment1.
您需要使用 .replace
来切换这两个片段,还需要将原始片段添加到Backstack中以便您可以调用它,并且您需要覆盖后退键操作才能发挥这种功能.看起来像这样(使用我的一个项目中的代码,使用支持库):
显示第一个片段:
菜单= new MenuFragment_Main();//实例化片段getSupportFragmentManager().beginTransaction().replace(R.id.pane,menu).commit();//显示片段
要将其交换为新片段并将其添加到后堆栈:
ListFragment_ShopListItem shoplist = new ListFragment_ShopListItem();//实例化片段getSupportFragmentManager().beginTransaction().replace(R.id.pane,shoplist).addToBackStack(null).commit();//用新片段替换原始片段,将原始片段添加到backstack
并覆盖返回键以返回上一个片段:
public void onBackPressed(){FragmentManager fm = getActivity().getSupportFragmentManager();fm.popBackStack();返回;}
I have the MainActivity, it contains ListFragment and framelayout, I am able to change the fragments on list on item click.
I have a problem to replace the existing Fragment1
with the new Fragment2
, on button click of Fragment1
, Fragment2
should replace the Fragment1
, and should have the same ListFragment at left, and back buttons should be properly handled,this means when I am in Fragment2
and press back button it should show the same ListFragment and Fragment1.
You need to use .replace
to switch the two fragments, you also need add add the original to the backstack so you can recall it, and you need to override the back key operation to function that way. It would look something like this (using code from one of my projects, using the support library):
To show your first fragment:
menu = new MenuFragment_Main(); // instantiate fragment
getSupportFragmentManager().beginTransaction().replace(R.id.pane, menu).commit(); // display fragment
To swap it for the new fragment and add it to the backstack:
ListFragment_ShopListItem shoplist = new ListFragment_ShopListItem(); // instantiate fragment
getSupportFragmentManager().beginTransaction().replace(R.id.pane, shoplist).addToBackStack(null).commit(); // replace original fragment with new fragment, add original to backstack
And to override the back key to go back to the previous fragment:
public void onBackPressed() {
FragmentManager fm = getActivity().getSupportFragmentManager();
fm.popBackStack();
return;
}
这篇关于片段替换现有片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!