標籤:android開發
Fragment的地位在開發中可是舉足輕重的,掌握它的的生命週期以及使用特性是非常重要的,例如在開發中常使用的模板:
點擊菜單,中心內容跟隨菜單變化,但是在菜單間切換時,需要儲存之前輸入的資訊或其他狀態,如果使用Fragment 的hide/show方法如下:
FragmentTransaction transaction = fragmentManager.beginTransaction();transaction.setCustomAnimations(R.anim.right_in, R.anim.left_fadeout,R.anim.right_fadein, R.anim.left_fadeout);transaction.hide(oldFragment);transaction.show(newFragment);transaction.commit();
但是使用這個中方法可能出現一個Bug:在菜單切換時如A-B-C切換,當顯示C內容時,A或B組件的資訊也可能顯示出來,並且還可以響應事件,對應用來說可是不能容忍的!
至於為什麼會出現這種問題的原因還沒有調查到,如果您知道,求告知求科普。。。
另一種方法就是使用replace的方式代替hide/show,重點是調用FragmentTransaction.addToBackStack()來儲存fragment的狀態,使用代碼如下:
private void replaceContainer(MenuItems menuItem) {FragmentTransaction transaction = fragmentManager.beginTransaction();transaction.setCustomAnimations(R.anim.right_in, R.anim.left_fadeout,R.anim.right_fadein, R.anim.left_fadeout);Fragment fragment = retrieveFromCache(menuItem);// fragment沒有執行個體化過,new出一個添加到FragmentTransaction中,並且儲存fragment的狀態if (null == fragment) {try {fragment = menuItem.getClazz().newInstance();transaction.addToBackStack(null);} catch (Exception e) {Log.e(TAG, "執行個體化菜單失敗");return;}}transaction.replace(R.id.content_frame, fragment);transaction.commit();}private Fragment retrieveFromCache(MenuItems menuItem) {//從fragmentManager中擷取已有的fragment對象for (Fragment backFragment : fragmentManager.getFragments()) {if (null != backFragment&& menuItem.getClazz().equals(backFragment.getClass())) {return backFragment;}}return null;}
不僅能儲存fragment的狀態,而且fragment的生命週期也能正常走動!!記得FragmentTransaction.addToBackStack()這個很重要哦!
Android fragment 使用replace並儲存狀態