2012-02-04 100 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() 
    } 
}