使用:
private Fragment fragment;
private FragmentManager fm;
fm = getSupportFragmentManager();
fragment = fm.findFragmentById(R.id.fragment_container);
fm.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();beginTransaction源码:
/**
* Start a series of edit operations on the Fragments associated with
* this FragmentManager.
*
* <p>Note: A fragment transaction can only be created/committed prior
* to an activity saving its state. If you try to commit a transaction
* after {@link FragmentActivity#onSaveInstanceState FragmentActivity.onSaveInstanceState()}
* (and prior to a following {@link FragmentActivity#onStart FragmentActivity.onStart}
* or {@link FragmentActivity#onResume FragmentActivity.onResume()}, you will get an error.
* This is because the framework takes care of saving your current fragments
* in the state, and if changes are made after the state is saved then they
* will be lost.</p>
*/
public abstract FragmentTransaction beginTransaction();add源码:
/**
* Calls {@link #add(int, Fragment, String)} with a null tag.
*/
public abstract FragmentTransaction add(@IdRes int containerViewId, Fragment fragment);commit源码:
/**
* Schedules a commit of this transaction. The commit does
* not happen immediately; it will be scheduled as work on the main thread
* to be done the next time that thread is ready.
*
* <p class="note">A transaction can only be committed with this method
* prior to its containing activity saving its state. If the commit is
* attempted after that point, an exception will be thrown. This is
* because the state after the commit can be lost if the activity needs to
* be restored from its state. See {@link #commitAllowingStateLoss()} for
* situations where it may be okay to lose the commit.</p>
*
* @return Returns the identifier of this transaction's back stack entry,
* if {@link #addToBackStack(String)} had been called. Otherwise, returns
* a negative number.
*/
public abstract int commit();

本文介绍如何在Android应用中使用Fragment及FragmentManager进行界面管理。详细解释了beginTransaction(), add() 和 commit() 方法的作用及其限制条件,帮助开发者更好地理解Fragment的生命周期。
&spm=1001.2101.3001.5002&articleId=80192576&d=1&t=3&u=8fc2d62b7c8e4e74a56c1a67a48f874a)

被折叠的 条评论
为什么被折叠?



