restore Fragment - Android User Interface

Android examples for User Interface:Fragment

Description

restore Fragment

Demo Code


//package com.java2s;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;

public class Main {
    public static void restoreFragment(Activity activity,
            Fragment fragment, int id, String tag, String[] hideTags) {
        FragmentManager fm = activity.getFragmentManager();
        Fragment fr = fm.findFragmentByTag(tag);
        FragmentTransaction ft = fm.beginTransaction();

        hideFragments(hideTags, fm, ft);

        if (fr != null) {
            reloadFragment(fragment, id, tag, fr, ft);
        } else {/*  w  w w.j  a  va  2  s  .  c  o  m*/
            ft.add(id, fragment, tag);
        }

        ft.commit();
    }

    private static void hideFragments(String[] hideTags,
            FragmentManager fm, FragmentTransaction ft) {
        for (String t : hideTags) {
            Fragment f = fm.findFragmentByTag(t);
            if (f != null) {
                ft.hide(f);
            }
        }
    }

    private static void reloadFragment(Fragment fragment, int id,
            String tag, Fragment fr, FragmentTransaction ft) {
        if (fr.isVisible()) {
            ft.remove(fr);
            ft.add(id, fragment, tag);
        } else {
            ft.show(fr);
        }
    }
}

Related Tutorials