求问Fragment fragment = (Fragment) page.getCls().newInstance();

jack
  • 283

这段代码是什么意思?里面的newInstance()的作用是什么?

这个是别人的代码:

 protected void initFromIntent(int pageValue, Intent data) {
        if (data == null) {
            throw new RuntimeException(
                    "you must provide a page info to display");
        }
        SimpleBackPage page = SimpleBackPage.getPageByValue(pageValue);
        if (page == null) {
            throw new IllegalArgumentException("can not find page by value:"
                    + pageValue);
        }

        setActionBarTitle(page.getTitle());

        try {
            /**
             *获得一个Fragment
             */
            Fragment fragment = (Fragment) page.getClz().newInstance();

            Bundle args = data.getBundleExtra(BUNDLE_KEY_ARGS);
            if (args != null) {
                fragment.setArguments(args);
            }

            FragmentTransaction trans = getSupportFragmentManager()
                    .beginTransaction();
            trans.replace(R.id.container, fragment, TAG);
            trans.commitAllowingStateLoss();

            mFragment = new WeakReference<Fragment>(fragment);
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException(
                    "generate fragment error. by value:" + pageValue);
        }
    }

通过调用getPageByValue()获得page

public enum SimpleBackPage {

    FEEDBACK(1, R.string.setting_about, FeedBackFragment.class),
    ABOUT(2, R.string.setting_about, AboutFrament.class);


    private int values;
    private int title;
    private Class<?> cls;

    private SimpleBackPage(int values, int title, Class<?> cls) {
        this.values = values;
        this.title = title;
        this.cls = cls;
    }

    public int getValues() {
        return values;
    }

    public void setValues(int values) {
        this.values = values;
    }

    public Class<?> getCls() {
        return cls;
    }

    public void setCls(Class<?> cls) {
        this.cls = cls;
    }

    public int getTitle() {
        return title;
    }

    public void setTitle(int title) {
        this.title = title;
    }

    public static SimpleBackPage getPageValue(int val) {
        for (SimpleBackPage p : values()) {
            if (p.getValues() == val) {
                return p;
            }
        }
        return null;
    }
}
回复
阅读 2.8k
2 个回答
有明
  • 26.6k
✓ 已被采纳

newInstance 是 Class 类的方法,作用是新建类的实例


从代码来看,这段代码是把多个Fragment的交互做了一个封装。

传入的参数是Fragment的Class定义,这样就能避免不必要的Fragment实例化,而通过Class去实例化Fragment则需要使用newInstance() 这个方法。

li21
  • 3.1k

根据问题追加的代码Update

SimpleBackPage是enum类型,意图是通过数字获取对应的Fragment类

SimpleBackPage page = SimpleBackPage.getPageValue(pageValue);
// 如果pageValue=1,getCls返回的就是FeedBackFragment.class
// 如果pageVaule=2,getCls返回的就是AboutFrament.class
page.getCls();

public enum SimpleBackPage {
    FEEDBACK(1, R.string.setting_about, FeedBackFragment.class),
    ABOUT(2, R.string.setting_about, AboutFrament.class);
    
    private SimpleBackPage(int values, int title, Class<?> cls) {
        this.values = values;
        this.title = title;
        this.cls = cls;
    }
    public Class<?> getCls() {
        return cls;
    }    

当拿到Fragment类后

Fragment.class.newInstance() 通过调用该类的无参数构造器,创建并返回该类的一个实例。
从结果上看等价于:new Fragment();

Returns a new instance of the class represented by this Class, created by invoking the default (that is, zero-argument) constructor. If there is no such constructor, or if the creation fails (either because of a lack of available memory or because an exception is thrown by the constructor), an InstantiationException is thrown. If the default constructor exists but is not accessible from the context where this method is invoked, an IllegalAccessException is thrown.

感觉上Fragment.class.newInstance()不如new Fragment()清楚明了。而且你还要为其添加try/catch exception type IllegalAccessException.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏