我在 Activity 中使用 ActionBar 并使用内部 TabListener:
public static class TabListener<T extends Fragment>
implements ActionBar.TabListener{
private final Activity myActivity;
private final String myTag;
private final Class<T> myClass;
public TabListener(Activity activity, String tag, Class<T> cls) {
myActivity = activity;
myTag = tag;
myClass = cls;
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. Usually do nothing.
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);
// Check if the fragment is already initialized
if (myFragment == null) {
// If not, instantiate and add it to the activity
myFragment = Fragment.instantiate(myActivity, myClass.getName());
myActivity.setTitle( myClass.getName());
ft.add(android.R.id.content, myFragment, myTag);
} else {
// If it exists, simply attach it in order to show it
myActivity.setTitle( myFragment.getClass().getName());
ft.attach(myFragment);
}
Log.i("current fragment", myFragment.getClass().toString());
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);
if (myFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(myFragment);
}
}
}
我需要从 DialogFragment 在当前选项卡上切换另一个 Fragment 。我这样做的常见方式是这样的:
Fragment newFragment = new ContactsArchiveFragment();
fragmentTransaction.replace(android.R.id.content, newFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
但是当我切换到另一个选项卡时,我当前的 Fragment(已切换到)没有分离并显示在上方。我该如何解决这个问题?