Android fragment 使用replace並儲存狀態

來源:互聯網
上載者:User

標籤: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並儲存狀態

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.