这段代码是什么意思?里面的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;
}
}
newInstance 是 Class 類別的方法,作用是新建類別的實例
從程式碼來看,這段程式碼是把多個Fragment的互動做了一個封裝。
傳入的參數是Fragment的Class定義,這樣就能避免不必要的Fragment實例化,而透過Class去實例化Fragment則需要使用newInstance() 這個方法。
依問題追加的程式碼Update
SimpleBackPage是enum類型,意圖是透過數字取得對應的Fragment類別:
拿到Fragment類別後
不如Fragment.class.newInstance()
透過呼叫該類別的無參數建構器,建立並傳回該類別的一個實例。從結果來看等價於:
new Fragment();
清楚明了。而且你還要為其添加try/catch
Fragment.class.newInstance()
.new Fragment()