文章出處
文章列表
一般寫程序時我們都是得到FragmentManager,然后開啟一個事務,然后進行Fragment的替換,然后提交事務。
//1.得到FragmentManger FragmentManager fm = getSupportFragmentManager(); // //2.開啟事務 FragmentTransaction transaction = fm.beginTransaction(); // //3.替換 transaction.replace(R.id.fl_content, fragment); // //4.提交事務 transaction.commit();
但是,在實際的開發中,這種方式會導致Fragment的頻繁創建,消耗用戶的流量,所有提出以下優化:
就是用Add()和Hide() ,講之前的Fragment隱藏,然后把要顯示的Fragment添加進去,當要顯示之前那個Fragment的時候,直接show()出來就可以了。
private void switchFrament(Fragment from,Fragment to) { if(from != to){ mContent = to; FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); //才切換 //判斷有沒有被添加 if(!to.isAdded()){ //to沒有被添加 //from隱藏 if(from != null){ ft.hide(from); } //添加to if(to != null){ ft.add(R.id.fl_content,to).commit(); } }else{ //to已經被添加 // from隱藏 if(from != null){ ft.hide(from); } //顯示to if(to != null){ ft.show(to).commit(); } } } }
提示:記得在add() Fragment的時候判斷是否為null.
文章列表
全站熱搜