2017-05-30 92 views
0

我有兩個片段,片段A和片段B.我使用添加片段方法主要活動手柄加載數據隨着片段返回堆棧

String backStateName = fragment.getClass().getName(); 
    FragmentManager fragmentManager = getSupportFragmentManager(); 
    boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStateName, 0); 

    if (!fragmentPopped) { 
     FragmentTransaction ft = fragmentManager.beginTransaction(); 
     ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); 
     ft.add(R.id.frame_container_admin, fragment, backStateName); 
     ft.addToBackStack(backStateName); 
     ft.commit(); 
    } 

在此之後,每當我從PRES片段BI回來要重新加載數據來自服務器。我該如何處理?

回答

1

在您的活動

創建backstackchange

getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() { 
      @Override 
      public void onBackStackChanged() { 
       try { 

        //Get current visible fragment 
        FragmentManager fragmentManager = ((AppCompatActivity) activity).getSupportFragmentManager(); 
        Fragment currentVisibleFragment = fragmentManager.findFragmentById(R.id.container_fragment); 


       if(currentVisibleFragment instanceof FragmentB){ 
        //Cast currentVisibleFragment to Fragment B and call method to request data again. 
        ((FragmentB)currentVisibleFragment).requestData(); 
       } 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
} 

收聽者與您的請求代碼創建在片段B中的請求數據的方法。

+0

但是,如果我必須使用多個片段,那麼我必須在onBackStackChanged()方法內創建多個if else語句嗎? –

+0

然後改爲添加一個片段替換它。並在onCreateView方法中寫入請求,因爲當您更換片段或片段時會彈出回棧中,每次調用onCreateView。 –

+0

好的,謝謝你對我有幫助.... :) –