我正在开发一个应用程序,其中我有一个侧边菜单。当单击每个项目时,片段将被替换为新的。
我有一种替换碎片的方法。但碎片重叠而不是替换。旧碎片位于背景中,新碎片位于旧碎片的顶部。
这是我替换片段的方法。
private void changeFragment(Fragment targetFragment){
resideMenu.clearIgnoredViewList();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment, targetFragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
如何在放置新片段之前清除旧片段?
编辑:
private void changeFragment(Fragment targetFragment){
resideMenu.clearIgnoredViewList();
FragmentTransaction ft = (FragmentTransaction) getSupportFragmentManager().beginTransaction();
Fragment prev = (Fragment) getSupportFragmentManager().findFragmentByTag("fragment");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
ft.commit();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment, targetFragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(null)
.commit();
}
答案 0 :(得分:0)
尝试使用此代码。只需删除以前的片段..:D
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
if(fragment instanceof MessageInbox ){
PRODUCT_FLAG=0;
}
ft.remove(fragment);
}
答案 1 :(得分:0)
我总是在创建标签时给它一个标签。之后更容易找到它。然后你可以使用这样的代码:
// DialogFragment.show() will take care of adding the fragment
// in a transaction. We also want to remove any currently showing
// dialog, so make our own transaction and take care of that here.
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
ft.commit();
// Create and show the dialog.
DialogFragment newFragment = new GrowLogDialogFragment();
newFragment.setTargetFragment(this, 1);
newFragment.show(getFragmentManager().beginTransaction(), "dialog");
答案 2 :(得分:0)
FragmentTransaction ft = getFragmentManager()
.beginTransaction();
ft.replace(R.id.main_fragment, targetFragment, "fragment");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);// this line do that
ft.commit();
答案 3 :(得分:0)
在onpause
或ondetach
@Override
public void onPause() {
// TODO Auto-generated method stub
try{
if (fragment != null) {
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
}
catch(Exception e)
{
e.printStackTrace();
}
Thread.interrupted();
super.onPause();
}
}