-
Replace One Fragment with Another
1.1 Keep in mind that when you perform fragment transactions, such as
replace or remove one, it's often appropriate to allow the user to navigate
backward and "undo" the change. To allow the user to navigate backward
through the fragment transactions, you must call addToBackStack() before
you commit the FragmentTransaction.
// Create fragment and give it an argument specifying the article it should
showArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION,position);
newFragment.setArguments(args);
FragmentTransaction transaction =getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate
backtransaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);//
transactiontransaction.commit();
The addToBackStack() method takes an optional string parameter that
specifies a unique name for the transaction. The name isn't needed unless
you plan to perform advanced fragment operations using the
FragmentManager.BackStackEntry APIs
调用addToBackStack()方法是为了能让用户使用回退键通过fragmentTransaction,返回到上一个fragment.
-
Communicating with other Fragments
2.1 在fragment中实现一个接口
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
2.2在onAttach(Activity activity)方法中判断宿主Activity是否已经实现了接口
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + "must
implement OnHeadlineSelectedListener");
}
}
2.3 在宿主Activity中,实现接口方法,添加逻辑代码