这段代码是什么意思?里面的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); } 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; } }
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.
Update code added based on the problem
SimpleBackPage is an enum type, and the intention is toget the corresponding Fragment class through numbers:
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();
It feels like
to itFragment.class.newInstance()
is not as clear asnew Fragment()
. And you also need to add try/catchexception type IllegalAccessException
.