每次切换Fragment的时候,默认Fragment都会重新实例化,重新加载一边数据,这样会消耗性能和数据流量。
fragment都add()进来后,用hide()和show()来切换fragment 并且不重新实例化:
public void switch(Fragment from, Fragment to) {
if (mFragment != to) {
mFragment = to;
FragmentTransaction transaction = mFragmentMnger.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新fragment
} else {
transaction.hide(from).show(to).commit(); // 隐藏from fragment,显示下to
}
}
}