片段相当难以使用,因此您应该了解它们。这是我的做法。
片段管理器:
public class FragmentsUtils {
private static String DIALOG_TAG = "dialog_tag";
/*public static MyAlertDialogFragment showDialog(FragmentManager fragmentManager, int id) {
// 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 = fragmentManager.beginTransaction();
Fragment prev = fragmentManager.findFragmentByTag(DIALOG_TAG);
if (prev != null) {
ft.remove(prev);
}
// ft.addToBackStack(null);
// Create and show the dialog.
MyAlertDialogFragment newFragment = MyAlertDialogFragment.newInstance(id);
newFragment.show(ft, DIALOG_TAG);
return newFragment;
}*/
public static void swapFragments(FragmentManager fragmentManager, int containerViewId, Fragment newFragment, String fragmentTag) {
if (fragmentManager == null)
return;
View newFragmentMainView = newFragment.getView();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// fragmentTransaction.replace(containerViewId, fragment);
if(fragmentTag == null || fragmentTag.length() < 1)
fragmentTransaction.add(containerViewId, newFragment);
else
fragmentTransaction.add(containerViewId, newFragment, fragmentTag);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.commit();
}
public static void swapFragments(FragmentManager fragmentManager, int containerViewId, Fragment newFragment) {
swapFragments(fragmentManager, containerViewId, newFragment, null);
}
}
这里是如何使用它:
WebViewDetailsActivity webViewDetailsActivity = new WebViewDetailsActivity();
Bundle args = new Bundle();
args.putString("url", tempRestModel.ClickTableUrl); webViewDetailsActivity.setArguments(args);
FragmentsUtils.swapFragments(getBaseFragmentManager(), R.id.realtabcontent, webViewDetailsActivity, Consts.TAB_REC);