create Fragment by Class name - Android java.lang.reflect

Android examples for java.lang.reflect:Class

Description

create Fragment by Class name

Demo Code


//package com.java2s;

import android.support.v4.app.Fragment;

import java.lang.reflect.Constructor;

public class Main {
    public static Fragment createFragment(String className) {
        try {//from   www.j  a  v  a 2 s.  com
            Class fragmentClass = Class.forName(className);
            return createFragment(fragmentClass);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

    }

    public static Fragment createFragment(Class fragmentClass) {
        try {
            Constructor<?> fragConstructor = fragmentClass.getConstructor();
            Object fragment = fragConstructor.newInstance();
            return (Fragment) fragment;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}

Related Tutorials