2014-11-08 109 views

回答

2

在onCreate中收到的Bundle包含最近提供的數據,如果重新創建活動並且getArguments Bundle返回作爲參數提供的bundle。

1

用於創建片段和創建片段的參數集不能再次設置。 onCreate/onCreateView/onActivityCreated/onViewStateRestored中的包是savedInstanceState。你可以使用這個獲得通過onSaveInstanceState覆蓋保留的持久值。在創建片段時,savedInstanceState包通常爲空,因此您可能需要使用getArguments。

有關getArguments的另一件事,你不必堅持這些值。他們將通過fragment code爲您重新創建。如果您嘗試setArguments上已經有他們一個片段,你會碰到一個IllegalStateException

19

TL; DR:

Fragment.getArguments()是最初創建一個片段。

onCreate(Bundle)用於從前一個實例中檢索Bundle。

詳細:

我已經沖刷了這個網站,並要求經驗豐富的Android開發者,所以這裏是一個體面的解釋:

的捆綁作爲的onCreate參數傳遞函數用於存在片段的前一個實例,該函數在調用函數時會更新。 (你可以更多關於這個讀了這裏的官方文檔:https://developer.android.com/training/basics/activity-lifecycle/recreating.html

Fragment.getArguments()功能然而,當最初創建片段使用。您將首次導航到片段,並且該片段的前一個實例將不存在。在這種情況下,您可以在使用setArguments()函數getArguments()函數共享的Fragment中設置局部變量。 (更多在這裏:https://developer.android.com/reference/android/app/Fragment.html

因此: 健壯的代碼看起來是這樣的:

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) 
{ 
    super.onCreateView(inflater, container, savedInstanceState); 

    mView = inflater.inflate(R.layout.fragment_name, container, false); 
    mContext = getActivity(); 

    if(savedInstanceState != null){ 
     Log.d("yourapp", "A SavedInstanceState exists, using past values"); 
     mValue = savedInstanceState.getString("valueString"); 
    }else{ 
     Log.d("yourapp", "A SavedInstanceState doesn't exist"); 
     Bundle bundle = getArguments(); 
     mValue = bundle.getString("valueString"); 
    } 
} 

負責處理這兩種情況下你的onCreate狀態。

希望這會有所幫助!

1

我想加到N15M0_jk的回答。 有時不需要保存片段狀態(對於靜態片段),並且只能使用進行重新創建,因爲即使在破壞之後仍然保留使用setArguments()設置的參數。

查看setArguments()

+0

感謝參考,你已經解決了我的頭痛,我不知道爲什麼是的onSaveInstanceState沒用! – Burrich 2017-12-28 12:58:50

相關問題