init Fragment - Android android.app

Android examples for android.app:Fragment

Description

init Fragment

Demo Code


//package com.java2s;

import android.content.Intent;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

public class Main {
    public static final String FRAGMENT_ARGS = "fragment_arg";
    public static final String FRAGMENT_NAME = "fragment_name";
    public static final String FRAGMENT_TAG = "fragment_tag";

    public static void initFragment(FragmentActivity activity,
            Intent intent, int containerId) {
        if (intent == null) {
            return;
        }/*from w ww. ja v  a 2s.  co m*/

        Bundle bundle = intent.getExtras();
        if (bundle == null) {
            return;
        }

        String fragmentName = bundle.getString(FRAGMENT_NAME);
        String fragmentTag = bundle.getString(FRAGMENT_TAG);
        Bundle fragmentArgs = bundle.getBundle(FRAGMENT_ARGS);

        FragmentManager fm = activity.getSupportFragmentManager();
        Fragment fragment = fm.findFragmentByTag(fragmentTag);
        if (fragment == null) {
            FragmentTransaction ft = fm.beginTransaction();
            fragment = Fragment.instantiate(activity, fragmentName,
                    fragmentArgs);
            ft.add(containerId, fragment, fragmentName);
            ft.commit();
        } else {
            if (fragment.isDetached()) {
                FragmentTransaction ft = fm.beginTransaction();
                ft.attach(fragment);
                ft.commit();
            }
        }
    }
}

Related Tutorials