Fragment切换返回
1.开发中遇到需要在Fragment之间切换,保存状态
(1).初始化Fragment:
1 public void initFragment(){ 2 FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 3 ft.replace(R.id.fl_container,onCreteFragment()); 4 ft.commitAllowingStateLoss();//允许丢失,一般可以不用这个采用commit()替代 5 }
(2).切换Fragment算法:
1 public void switchFragment(Fragment from, Fragment to) { 2 FragmentTransaction mFragmentTransaction = getSupportFragmentManager().beginTransaction(); 3 if (!to.isAdded()) { // 先判断是否被add过 4 mFragmentTransaction.hide(from).add(R.id.fl_container, to) 5 .commit(); // 隐藏当前的fragment,add下一个到Activity中 6 } else { 7 mFragmentTransaction.hide(from).show(to).commit(); // 隐藏当前的fragment,显示下一个 8 } 9 }
(3).封装返回监听,采用弱引用和静态内部类,避免内存泄漏
1 public static class MyOnBackListener implements BaseFragment.OnBackListener { 2 private final WeakReference<BaseFragment> mBaseFragment;//目的Fragment 3 private final WeakReference<BaseFragmentActivity> mBaseActivity; 4 /** 5 * @param toFragment 跳转目的Fragment 6 * @param baseActivit 当前BaseActivity 7 */ 8 public MyOnBackListener(BaseFragment toFragment,BaseFragmentActivity baseActivit) { 9 mBaseFragment =new WeakReference<>(toFragment); 10 mBaseActivity =new WeakReference<>(baseActivit); 11 } 12 13 @Override 14 public void back(BaseFragment baseFragment) { 15 BaseFragmentActivity baseActivity = mBaseActivity.get(); 16 BaseFragment baseFragment2 = mBaseFragment.get(); 17 if (baseActivity !=null&& baseFragment2 !=null&&baseFragment!=null){ 18 baseActivity.switchFragment(baseFragment,baseFragment2); 19 } 20 } 21 }
(4).Activity中简单使用:
private void initLocalFragment() { mRfbf = new RecyclerFabBehaviorFragment(); mRfbf.setOnBackListener(new MyOnBackListener(mStartRecycFragment,this)); }
1 @Override 2 public void click(View view, int position) { 3 switch (position){ 4 case 0: 5 switchFragment(mStartRecycFragment, mRfbf); 6 break; 7 } 8 }
(5).子类Fragment中记得调用back:eg
TabyoutViewPagerFragment extends BaseFragment
private void initToolbar() { mToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mOnBackListener!=null){ mOnBackListener.back(TabyoutViewPagerFragment.this); } } }); }
(6).可以采用鸿阳的FABridge来简化Fragment中定义接口在Activity中回调
annotationProcessor 'com.zhy.fabridge:fabridge-compiler:1.0.0'
implementation 'com.zhy.fabridge:fabridge-api:1.0.0'
Fragment中定义
Fabridge.call(getActivity(), EVENT_CLICK, "来了");
Activity中使用
@FCallbackId(id = FabrigeSampleFragment.EVENT_CLICK) public void menuItemClick(String title) { Toast.makeText(this, ""+title+","+Thread.currentThread().getName(), Toast.LENGTH_SHORT).show(); }