Fragment碎片频繁来回切换的时候报java.lang.IllegalStateException: No activity

出现这个问题的原因是因为使用的transcation.replace(fragmentTwo);的方式进行碎片切换的。

解决方案是使用add和show、hide方法组合实现碎片的切换(应该是显示、隐藏)。

我这里使用的是RadioButton控件的Id值。

/**
     * 切换碎片:使用show和hide以及add,不要使用replace(频繁来回切换的时候容易发生内存溢出的错误)
     */
    public void onTabSelected(int radioGroupId) {
        //开启一个事务
        FragmentTransaction transcation = fragmentManager.beginTransaction();
        //设置淡入淡出效果
        transcation.setCustomAnimations(android.R.animator.fade_in,android.R.animator.fade_out);
        //隐藏全部碎片
        hideFragments(transcation);
        //有选择的显示碎片
        switch (radioGroupId) {
        
            case R.id.home:
                if(fragmentOne == null){
                    fragmentOne = new FragmentOne();
                    transcation.add(R.id.center_layout, fragmentOne);
                }else{
                    transcation.show(fragmentOne);
                }
                break;
                
            case R.id.category:
                if(fragmentTwo == null){
                    fragmentTwo = new FragmentTwo();
                    transcation.add(R.id.center_layout, fragmentTwo);
                }else{
                    transcation.show(fragmentTwo);
                }
                break;
                
            case R.id.collect:
                if(fragmentThree == null){
                    fragmentThree = new FragmentThree();
                    transcation.add(R.id.center_layout, fragmentThree);
                }else{
                    transcation.show(fragmentThree);
                }
                break;
                
            case R.id.setting:
                if(fragmentFour == null){
                    fragmentFour = new FragmentFour();
                    transcation.add(R.id.center_layout, fragmentFour);
                }else{
                    transcation.show(fragmentFour);
                }
                break;
                
            default:
                break;
        }
        transcation.commitAllowingStateLoss();
    }
    
    /**隐藏全部碎片
     * 需要注意:不要在OnResume方法中实例化碎片,因为先添加、显示,才可以隐藏。否则会出现碎片无法显示的问题*/
    private void hideFragments(FragmentTransaction transaction) {
        if (null != fragmentOne) {
            transaction.hide(fragmentOne);
        }
        if (null != fragmentTwo) {
            transaction.hide(fragmentTwo);
        }
        if (null != fragmentThree) {
            transaction.hide(fragmentThree);
        }
        if (null != fragmentFour) {
            transaction.hide(fragmentFour);
        }
    }

需要注意,不要在OnResume方法中实例化碎片。

// 存放底部菜单的各个RadioButton的Id值
    private int[] radioButtonIds = {R.id.home,R.id.category,R.id.collect,R.id.setting};


@Override
    protected void onResume() {
        
        //切换碎片
        onTabSelected(radioButtonIds[0]);
        
        super.onResume();
    }

 

posted @ 2015-09-08 16:35  HaiyuKing  阅读(1394)  评论(0编辑  收藏  举报