1.fragment里嵌套fragment时,最好使用getChildFragmentManager()方法来获取FragmentManager。比较没有坑
2.获取FragmentManager的方法有3中:
getChildFragmentManager();(只用于Fragment)
getFragmentManager();(只用于非FragmentActivity的Activity)
getSupportFragmentManager();(只用于FragmentActivity的Activity)
3.合理使用Tag
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
NativeLibrary.ndkInit(this);
mCameraFragment = (CameraFragment) getSupportFragmentManager().findFragmentByTag(CameraFragment.TAG);
if (mCameraFragment == null) {
mCameraFragment = new CameraFragment();
Bundle bundle = new Bundle();
bundle.putParcelable(CameraFragment.ACTIVITY_INTENT, getIntent());
mCameraFragment.setArguments(bundle);
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.rl_root, mCameraFragment, CameraFragment.TAG)
.commitAllowingStateLoss();
}
4.关于getFragmentManager()与getChildFragmentManager():
// Fragment.java
// The fragment manager we are associated with. Set as soon as the
// fragment is used in a transaction; cleared after it has been removed
// from all transactions.
FragmentManagerImpl mFragmentManager;
/**
* Return the FragmentManager for interacting with fragments associated
* with this fragment's activity. Note that this will be non-null slightly
* before {@link #getActivity()}, during the time from when the fragment is
* placed in a {@link FragmentTransaction} until it is committed and
* attached to its activity.
*
* <p>If this Fragment is a child of another Fragment, the FragmentManager
* returned here will be the parent's {@link #getChildFragmentManager()}.
*/
final public FragmentManager getFragmentManager() {
return mFragmentManager;
}
// Fragment.java
// Private fragment manager for child fragments inside of this one.
FragmentManagerImpl mChildFragmentManager;
/**
* Return a private FragmentManager for placing and managing Fragments
* inside of this Fragment.
*/
final public FragmentManager getChildFragmentManager() {
if (mChildFragmentManager == null) {
instantiateChildFragmentManager();
if (mState >= RESUMED) {
mChildFragmentManager.dispatchResume();
} else if (mState >= STARTED) {
mChildFragmentManager.dispatchStart();
} else if (mState >= ACTIVITY_CREATED) {
mChildFragmentManager.dispatchActivityCreated();
} else if (mState >= CREATED) {
mChildFragmentManager.dispatchCreate();
}
}
return mChildFragmentManager;
}
void instantiateChildFragmentManager() {
if (mHost == null) {
throw new IllegalStateException("Fragment has not been attached yet.");
}
mChildFragmentManager = new FragmentManagerImpl();
mChildFragmentManager.attachController(mHost, new FragmentContainer() {
@Override
@Nullable
public View onFindViewById(int id) {
if (mView == null) {
throw new IllegalStateException("Fragment does not have a view");
}
return mView.findViewById(id);
}
@Override
public boolean onHasView() {
return (mView != null);
}
}, this);
}
网友评论