我有一個名爲TheParent的父DialogFragment和一個名爲TheChild的擴展了TheParent的子片段。當創建擴展父片段的子片段時調用newInstance()
不過,我需要能夠以初始化所在的當前一些變量即使我實例TheChild,所以我試着爲:
在父
public static TheParent newInstance(int myInt) {
Bundle args = new Bundle();
TheParent fragment = new TheParent();
args.putInt(ARGUMENT_MYINT, myInt);
fragment.setArguments(args);
return fragment;
}
,然後在孩子:
public static TheChild newInstance(int myInt) {
return super.newInstance(myInt);
}
但它不喜歡我這樣做是因爲靜態上下文。
在TheChild上調用newInstance()並讓它調用父類的newInstance()的正確方法是什麼?
那麼,如果父母需要參數才能設置,我該如何正確地聲明/設置孩子?父類需要myInt –
將初始化代碼放在父類中的一個採用int的私有構造函數中。然後從TheParent.newInstance調用該構造函數並將其傳遞給myInt。然後,在TheChild類中,您將需要一個構造函數,該構造函數還需要一個int並調用super(myInt),它是您剛剛創建的父構造函數,並且在TheChild.newInstance中,您將在TheChild中調用此構造函數並將其傳遞給myInt。通過這種方式,孩子和父母都將運行父母初始化代碼,並且在TheChild中創建的片段將是TheChild類型而不是TheParent。 –