-
Notifications
You must be signed in to change notification settings - Fork 11
Fragment
- 《Fragment详解之一——概述》
- 《Fragment详解之二——基本使用方法》
- 《Fragment详解之三——管理Fragment(1)》
- 《Fragment详解之四——管理Fragment(2)》
- 《Fragment详解之五——Fragment间参数传递》 Fragment跳转时传递参数及结果回传的方法
- 《Fragment详解之六——如何监听fragment中的回退事件与怎样保存fragment状态》
切换Fragment时实现数据保持
public void switchContent(Fragment from, Fragment to) {
if (mContent != to) {
mContent = to;
FragmentTransaction transaction = mFragmentMan.beginTransaction().setCustomAnimations(
android.R.anim.fade_in, R.anim.slide_out);
if (!to.isAdded()) { // 先判断是否被add过
transaction.hide(from).add(R.id.content_frame, to).commit(); // 隐藏当前的fragment,add下一个到Activity中
} else {
transaction.hide(from).show(to).commit(); // 隐藏当前的fragment,显示下一个
}
}
}
其中,下面的代码很关键,没有下面的代码会出现切换tab的时候重影现象:
@Override public void setMenuVisibility(boolean menuVisible) { super.setMenuVisibility(menuVisible); if (this.getView() != null) this.getView().setVisibility(menuVisible ? View.VISIBLE : View.GONE); }
让多个Fragment 切换时不重新实例化
实例
https://github.com/MostafaGazar/soas/blob/master/app/src/main/java/com/meg7/soas/ui/fragment/retained/PhotosListTaskFragment.java
https://github.com/MostafaGazar
场景演示 : 切换到该Fragment 11-29 14:26:35.095: D/AppListFragment(7649): onAttach 11-29 14:26:35.095: D/AppListFragment(7649): onCreate 11-29 14:26:35.095: D/AppListFragment(7649): onCreateView 11-29 14:26:35.100: D/AppListFragment(7649): onActivityCreated 11-29 14:26:35.120: D/AppListFragment(7649): onStart 11-29 14:26:35.120: D/AppListFragment(7649): onResume 屏幕灭掉: 11-29 14:27:35.185: D/AppListFragment(7649): onPause 11-29 14:27:35.205: D/AppListFragment(7649): onSaveInstanceState 11-29 14:27:35.205: D/AppListFragment(7649): onStop
屏幕解锁 11-29 14:33:13.240: D/AppListFragment(7649): onStart 11-29 14:33:13.275: D/AppListFragment(7649): onResume
切换到其他Fragment: 11-29 14:33:33.655: D/AppListFragment(7649): onPause 11-29 14:33:33.655: D/AppListFragment(7649): onStop 11-29 14:33:33.660: D/AppListFragment(7649): onDestroyView
切换回本身的Fragment: 11-29 14:33:55.820: D/AppListFragment(7649): onCreateView 11-29 14:33:55.825: D/AppListFragment(7649): onActivityCreated 11-29 14:33:55.825: D/AppListFragment(7649): onStart 11-29 14:33:55.825: D/AppListFragment(7649): onResume 回到桌面 11-29 14:34:26.590: D/AppListFragment(7649): onPause 11-29 14:34:26.880: D/AppListFragment(7649): onSaveInstanceState 11-29 14:34:26.880: D/AppListFragment(7649): onStop 回到应用 11-29 14:36:51.940: D/AppListFragment(7649): onStart 11-29 14:36:51.940: D/AppListFragment(7649): onResume
退出应用 11-29 14:37:03.020: D/AppListFragment(7649): onPause 11-29 14:37:03.155: D/AppListFragment(7649): onStop 11-29 14:37:03.155: D/AppListFragment(7649): onDestroyView 11-29 14:37:03.165: D/AppListFragment(7649): onDestroy 11-29 14:37:03.165: D/AppListFragment(7649): onDetach
比Activity多了一些生命周期,完整和Activity对接上,大家好好利用。