FragmentPagerAdapter使用遇到的问题、instantiate

一直以来都这么用突然发现有问题

继承FragmentPagerAdapter重写getItem(int arg0)方法返回一个Fragment类型的对象

我一直以来都是直接new的,会new出很多吗?

如:

Fragment mFragment = null;
mFragment=new Fragment();

然后return 这个mFragment对象,如果你有多个Fragment片段,可以根据getItem方法的参数进行判断,这样用的意思是每次碰到这个索引都会创建一个Fragment,理论上是这样的,这样对于Adapter来说并不是一件好事,那么事实真的是这样么?我们唉看看Fragment的onCreateView方法:

如:

 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
        if (!"fragment".equals(name)) {
            return onCreateView(name, context, attrs);
        }
...
...
        if (fragment == null) {
            fragment = Fragment.instantiate(this, fname);
            fragment.mFromLayout = true;
...
...
}
onCreateView方法中当fragment==null时调用了Fragment.instantiate(this,fname);那么这个instantiate又是啥呢?继续往下看

public static Fragment instantiate(Context context, String fname, Bundle args) {
    try {
        Class clazz = sClassMap.get(fname);
        if (clazz == null) {
            // Class not found in the cache, see if it's real, and try to add it
            clazz = context.getClassLoader().loadClass(fname);
            if (!Fragment.class.isAssignableFrom(clazz)) {
                throw new InstantiationException("Trying to instantiate a class " + fname
                        + " that is not a Fragment", new ClassCastException());
            }
            sClassMap.put(fname, clazz);
        }
        Fragment f = (Fragment)clazz.newInstance();
        if (args != null) {
            args.setClassLoader(f.getClass().getClassLoader());
            f.mArguments = args;
        }
        return f;
    } catch (ClassNotFoundException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": make sure class name exists, is public, and has an"
                + " empty constructor that is public", e);
    } catch (java.lang.InstantiationException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": make sure class name exists, is public, and has an"
                + " empty constructor that is public", e);
    } catch (IllegalAccessException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": make sure class name exists, is public, and has an"
                + " empty constructor that is public", e);
    }
}
instaintiate方法返回一个Fragment对象,sClassMap是一个private static final ArrayList> 里面装的全是加载过的Fragment

GetClassLoager().loadClass("name")通过类的名字来加载一个Class

instaintiate是一个静态方法,所以通过new 来创建Fragment 自然会调用onCreateView,也就不会重复的去创建Fragment了。

转载于:https://www.cnblogs.com/gmm283029/p/4498965.html

你可能感兴趣的:(FragmentPagerAdapter使用遇到的问题、instantiate)