fragment大家經常應用到 聲明週期依賴於宿主activity
1 第一種用法:切換fragment
/**
使用replace方法
*/
private void showMyFragment(Fragment fragment) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.layout_fragment, fragment);
transaction.commit();}
這種方法如果切換的fragment進行請求網絡等會消耗流量和性能
2 第二種用法:add hide show------onHiddenChange()
使用場景:add hide show進行fragment切換的時候
所以按照google老大哥的方式 添加使用add 隱藏使用hide 需要判斷是否添加 如果添加直接show
/**
* 修改顯示的內容 不會重新加載
* newFragmeent 下一個fragment
* currentFrament 當前的fragment
*/
private void switchFragment(Fragment newFragmeent) {
if (newFragmeent != currentFrament ) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
if (!newFragmeent.isAdded()) { // 判斷是否被add過
// 隱藏當前的fragment,將 下一個fragment 添加進去
transaction.hide(currentFrament).add(R.id.layout_content, newFragmeent).commit();
} else {
// 隱藏當前的fragment,顯示下一個fragment
transaction.hide(currentFrament).show(newFragmeent).commit();
}
currentFrament = newFragmeent
}}
使用add hide() show()方法切換fragment 不會走任何的生命週期 無法通過生命週期進行刷新
這個時候另一個方法就派上用處了 我們的主題之一:onHiddenChanged()
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);if (hidden) { // 不在最前端顯示 相當於調用了onPause();
//做一些事情 你懂得
return;
}else{ // 在最前端顯示 相當於調用了onResume();
//數據刷新做一些自己的事情--你懂得
}}
3 setUservisibleHint()
使用場景:當fragment結合viewpager使用的時候 這個方法會調用
這個方法是在oncreateView之前使用 不要使用控件
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getUserVisibleHint()) {
//界面可見
} else {
//界面不可見 相當於onpause
}
}
尊重作者勞動成果:https://blog.csdn.net/kristch_wu/article/details/80000148