fragment overlapping when back key was pressed

if we can track what the current visible fragment is, then there is no problem. we can just hide or remove the current then show or add whatever fragment we want. but I found it's a little bit inconvenient to track which fragment will display when using addtobackstack function and back key was pressed.

solution: keep all created fragment in an array, when we want to display a new one, firstly find out which is currently visible in the array, disable it then do what we want.

        // find out current visible fragment and disable it, fragments is a array list
        Iterator<Fragment> iterator = fragments.iterator();
        while (iterator.hasNext()) {
            Fragment f = iterator.next();
            if (f == null || f.isDetached()) {
                // detached means the fragment is destroyed, no need to check anymore
                iterator.remove();
                continue;
            }
            if (f.isVisible()) {
                // if it's a song list, remove it so that when it come back, it will reload it's UI in oncreateview method
                if (f.getTag().equals(Filter.FilterType.Song.getTag()))
                    transaction.remove(f);
                else
                    transaction.hide(f);
                // there is only one fragment visible, can break now
                break;
            }
        }






你可能感兴趣的:(android,Fragment)