2012-02-04 149 views
4

我打算在具有包含在一個活動中3個fragmentlists。目標是您從第一個列表中選擇通話選項,然後根據您在通話列表中單擊的內容切換到運行列表,然後在運行列表中根據您點擊的內容轉換到最終用餐列表。這應該發生在片段本身(就像我擁有它)或調用活動來處理來回片段傳遞的數據?片段管理最佳實踐多ListFragments

public class OptionsActivity extends Activity { 

    protected TalkFragment talk; 
    protected RunFragment run; 
    protected EatFragment eat; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     talk = new TalkFragment(); 
     run = new RunFragment(); 
     eat = new EatFragment(); 
    } 
} 


public class TalkFragment extends ListFragment { 
    private Cursor mCursor; 
    int mCurCheckPosition = 0; 

    @Override 
    public void onActivityCreated(Bundle savedState) { 
     super.onActivityCreated(savedState); 

    } 
    @Override 
    public void onListItemClick(ListView l, View v, int pos, long id) { 
     mCurCheckPosition = pos; 
     // We can display everything in-place with fragments. 
     // Have the list highlight this item and show the data. 
     getListView().setItemChecked(pos, true); 

     // Check what fragment is shown, replace if needed. 
     RunFragment run_frag = (RunFragment) getFragmentManager().findFragmentById(R.id.fragment_run); 
     if (run_frag == null || run_frag.getShownIndex() != pos) { 
      run_frag = RunFragment.newInstance(pos); 
      FragmentTransaction ft = getFragmentManager().beginTransaction(); 
      ft.replace(R.id.details, details); 
      ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); 
      ft.commit(); 
     } 

    } 
} 

這顯然只是snippits,但你明白了。如果我這樣做,我不確定如何通過某些參數來正確分割。理想情況下,RunFragment會根據TalkFragment中所點擊的項目的ID知道要顯示的內容。這些應該通過活動而不是?

回答

2

我通常採用的方式是有活性的處理片段的交通警察。你onListItemClick實施能告訴活動是什麼想做的事:

public class OptionsActivity extends Activity { 

    protected TalkFragment talk; 
    protected RunFragment run; 
    protected EatFragment eat; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     talk = new TalkFragment(); 
     run = new RunFragment(); 
     eat = new EatFragment(); 
    } 

    public void showRunFragment() { 
     showFragment(R.id.fragment_run); 
    } 

    public void showEatFragment() { 
     showFragment(R.id.fragment_eat); 
    } 

    public void showFragment(int fragmentId) { 
     // Check what fragment is shown, replace if needed. 

     ... 
    } 
} 


public class TalkFragment extends ListFragment { 
    private Cursor mCursor; 
    int mCurCheckPosition = 0; 

    @Override 
    public void onActivityCreated(Bundle savedState) { 
     super.onActivityCreated(savedState); 

    } 

    @Override 
    public void onListItemClick(ListView l, View v, int pos, long id) { 
     mCurCheckPosition = pos; 
     // We can display everything in-place with fragments. 
     // Have the list highlight this item and show the data. 
     getListView().setItemChecked(pos, true); 

     getActivity().showRunFragment() 
    } 
}