2016-04-30 95 views
0

我有一個名爲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()的正確方法是什麼?

回答

1

靜態方法,如TheParent中的新實例是「類」方法。因此,不應該調用super.newInstance,而應該調用TheParent.newInstance(...)。記住調用靜態方法的方法是使用類名。希望能幫助到你。 所有這一切,TheChild中的newInstance方法都有一個類型爲「TheChild」的返回值。這意味着返回一個「TheParent」實例將是不可能的,這會導致編譯時錯誤,只要您將TheChild中的代碼從: 「return super.newInstance()」更改爲「TheParent.newInstance ()」。

+0

那麼,如果父母需要參數才能設置,我該如何正確地聲明/設置孩子?父類需要myInt –

+0

將初始化代碼放在父類中的一個採用int的私有構造函數中。然後從TheParent.newInstance調用該構造函數並將其傳遞給myInt。然後,在TheChild類中,您將需要一個構造函數,該構造函數還需要一個int並調用super(myInt),它是您剛剛創建的父構造函數,並且在TheChild.newInstance中,您將在TheChild中調用此構造函數並將其傳遞給myInt。通過這種方式,孩子和父母都將運行父母初始化代碼,並且在TheChild中創建的片段將是TheChild類型而不是TheParent。 –

0

這是我做的,從不必重複所有的邏輯在子類中保持:

public static TheChild newInstance(int myInt) { 
    TheChild fragment = new TheChild(); 
    fragment.setArguments(TheParent.newInstance(myInt).getArguments()); 
    return fragment; 
} 

當然,這種解決方案創建的TheParent第二個實例瞬間。