Home  >  Q&A  >  body text

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

这段代码是什么意思?里面的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;
    }
}
伊谢尔伦伊谢尔伦2759 days ago671

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 14:48:21

    newInstance is a method of the Class class, which is used to create new instances of the class


    From the code point of view, this code encapsulates the interaction of multiple Fragments.

    The parameter passed in is the Class definition of Fragment, which can avoid unnecessary instantiation of Fragment. To instantiate Fragment through Class, you need to use the newInstance() method.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 14:48:21

    Update code added based on the problem

    SimpleBackPage is an enum type, and the intention is to get the corresponding Fragment class through numbers :

    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;
        }    

    After getting the Fragment class

    Fragment.class.newInstance() Creates and returns an instance of this class by calling its parameterless constructor.
    The result is equivalent to: 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.

    It feels like Fragment.class.newInstance() is not as clear as new Fragment(). And you also need to add try/catch exception type IllegalAccessException.

    to it

    reply
    0
  • Cancelreply