2015-09-30 21 views
0

在我的應用程序中,我的活動有一個帶有片段的容器。當點擊該片段中的按鈕時,我會向容器中添加一個新片段,並將前一個片段添加到後臺堆棧中。檢測一個片段再次在頂部(有焦點)

FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 
    fragmentTransaction.add(R.id.primary_fragment_container, homeFragmentHandler); 
    fragmentTransaction.addToBackStack(folderId.toString()); 
    fragmentTransaction.commit(); 

結果是按回來關閉頂部片段,並返回到前一個片段,這正是我想要的。但是此時應該刷新片段上的某些元素。當用戶點擊並返回到前一個片段時,我怎麼知道要刷新該片段中的數據?這種情況下是否有onResume()方法?

+1

片段確實有一個onResume方法。它非常適合你的需要。 – FWeigl

+0

@Ascorbin在這種情況下沒有調用onResume方法。看起來,添加新片段時,以前的片段從未實際暫停,因此永遠不必恢復。 – BooleanCheese

+1

通過將數據作爲一個包傳遞,U可以從片段移動到片段。類似於從活動發送到活動的數據是意圖。每次創建原始片段,獲取意圖並檢查數據。如果它來自第二個片段,則重新加載所需的任何數據。 –

回答

1

你有適當的片段加入堆棧中:

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 

      MyFragment fragment = new MyFragment(); 

    transaction.replace(R.id.primary_fragment_container, fragment).addToBackStack(null).commit(); 
+0

做一個替換而不是一個添加意味着我的片段被(可能)被銷燬,在我的情況下是完美的,並且是最簡單的解決方案,因爲現在加載碎片的所有邏輯都發生了。謝謝! – BooleanCheese

+0

@BooleanCheese,但它不回答你原來的問題,現在你必須重建完整的片段 – hcpl

1
Fragment homeFragmentHandler= new Fragment(); 
    Bundle bundle = new Bundle(); 
    //replace this line below wth something convinient 
    bundle.putInt("key", value); 
    fragment.setArguments(bundle); 
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 
    fragmentTransaction.add(R.id.primary_fragment_container, homeFragmentHandler); 
    fragmentTransaction.addToBackStack(folderId.toString()); 
    fragmentTransaction.commit(); 

這將發送關於該片段/活動造成以前的片段加載數據。現在在onCreate添加此代碼來檢查捆綁中的數據

//In the onCreate of the original fragment 
Bundle bundle = this.getArguments(); 
if(bundle.getInt(key, defaultValue)!=null{ 
int myInt = bundle.getInt(key, defaultValue); 
// Load the data that needs to be refreshed when original fragment is loaded from the second one 
} 

不需要其他語句。如果片段是由任何其他activity/fragment構成的,那麼bundle.getInt將返回null,因此語句內的代碼不會被執行。