簡體   English   中英

找出添加了哪些活動片段

[英]Find out in which activity fragment was added

因此,基本上,我在兩個不同的活動中使用相同類型的片段,並且僅當片段是從特定活動中添加的時,我才想在片段中創建和初始化一些變量。 我的問題是如何以編程方式找出將片段添加到哪個活動中。

有兩種主要的實現方法:

較少模塊化的方法,您只需使用instanceof檢查

if(getActivity() instanceof MyActivity)

以及更模塊化的方法,在將片段添加到事務中的那一刻,您將一些參數傳遞給該片段:

// this during the transaction to pass extra parameters to the fragment
Fragment f = new MyFragment();
Bundle b = new Bundle();
b.putBoolean("doExtraCode", true);
f.setArguments(b);

然后在片段內:

// check if should execute extras
Bundle b = getArguments();
boolean doExtraCode = b == null? false: b.getBoolean("doExtraCode", false);

暫無
暫無

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

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