簡體   English   中英

Java的新手-創建片段時了解newInstance()

[英]new to java - understanding newInstance() when creating a fragment

在創建一個新的片段時,此類的構造函數具有這個newInstance ,但我不確定它的作用,也許您可​​以向我解釋它的作用?

public class DetailsFragment extends Fragment {
private int mIndex = 0;

public static DetailsFragment newInstance(int index) {

DetailsFragment df = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
df.setArguments(args);
return df;
}

public static DetailsFragment newInstance(Bundle bundle) {
int index = bundle.getInt("index", 0);
return newInstance(index);
}

根據我對Java的有限了解,我認為它正在創建此類的新對象。但是,既然如此,那為什么不在main中只寫DetailsFragment df = new DetailsFragment()呢? 似乎正在做某事。

newInstance函數是在Android中慣用的便捷函數。 該函數的目的是確保在創建片段時始終調用setArguments ,因為片段需要這些參數。 你是對的,你是不是這樣做事需要 這只是一種習慣模式。

您不能只創建帶有參數的構造函數,因為Android需要能夠實例化這些片段,並且它不能提供這些參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM