Tries to find the fragment, and if the fragment is not committed, instantiates it - Android User Interface

Android examples for User Interface:Fragment

Description

Tries to find the fragment, and if the fragment is not committed, instantiates it

Demo Code


import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;

public class Main{
    public static final String TAG = FragmentHelper.class.getSimpleName();
    /**//from www .  j av a 2 s  .co m
     * Tries to find the fragment, and if the fragment is not committed, instantiates it
     * @return existing fragment or a new instance, if it does not exist yet
     * */
    public static Fragment byTag(Activity activity, String tag, Class clazz) {
        Fragment f = byTag(activity, tag);
        if (f == null) {
            try {
                f = (Fragment) clazz.newInstance();
            } catch (InstantiationException e) {
                Log.e(TAG, "instantiation failed", e);
            } catch (IllegalAccessException e) {
                Log.e(TAG, "access exception", e);
            }
        }
        return f;
    }
    /**
     * Tries to find the fragment, and if the fragment is not committed, returns null
     * @return existing fragment or null
     * */
    public static Fragment byTag(Activity activity, String tag) {
        return ((ActionBarActivity) activity).getSupportFragmentManager()
                .findFragmentByTag(tag);
    }
}

Related Tutorials