與activity通訊
盡管fragment的實現是獨立於activity的,可以被用於多個activity,但是每個activity所包含的是同一個fragment的不同的實例。
Fragment可以調用getActivity()方法很容易的得到它所在的activity的對象,然后就可以查找activity中的控件們(findViewById())。例如:
ViewlistView =getActivity().findViewById(R.id.list);
同樣的,activity也可以通過FragmentManager的方法查找它所包含的frament們。例如:
ExampleFragment fragment=(ExampleFragment)getFragmentManager().findFragmentById(R.id.example_fragment
activity響應fragment的事件
有時,你可能需要fragment與activity共享事件。一個好辦法是在fragment中定義一個回調接口,然后在activity中實現之。
例如,還是那個新聞程序的例子,它有一個activity,activity中含有兩個fragment。fragmentA顯示新聞標題,fragmentB顯示標題對應的內容。fragmentA必須在用戶選擇了某個標題時告訴activity,然后activity再告訴fragmentB,fragmentB就顯示出對應的內容(為什么這么麻煩?直接fragmentA告訴fragmentB不就行了?也可以啊,但是你的fragment就減少了可重用的能力。現在我只需把我的事件告訴宿主,由宿主決定如何處置,這樣是不是重用性更好呢?)。如下例,OnArticleSelectedListener接口在fragmentA中定義:
public static class FragmentA extends ListFragment{
...
//Container Activity must implement this interface
public interface OnArticleSelectedListener{
public void onArticleSelected(Uri articleUri);
}
...
}
然后activity實現接口OnArticleSelectedListener,在方法onArticleSelected()中通知fragmentB。當fragment添加到activity中時,會調用fragment的方法onAttach(),這個方法中適合檢查activity是否實現了OnArticleSelectedListener接口,檢查方法就是對傳入的activity的實例進行類型轉換,如下所示:
public static class FragmentA extends ListFragment{
OnArticleSelectedListener mListener;
...
@Override
public void onAttach(Activity activity){
super.onAttach(activity);
try{
mListener =(OnArticleSelectedListener)activity;
}catch(ClassCastException e){
throw new ClassCastException(activity.toString()+"must implement OnArticleSelectedListener");
}
}
...
}
如果activity沒有實現那個接口,fragment拋出ClassCastException異常。如果成功了,mListener成員變量保存OnArticleSelectedListener的實例。於是fragmentA就可以調用mListener的方法來與activity共享事件。例如,如果fragmentA是一個ListFragment,每次選中列表的一項時,就會調用fragmentA的onListItemClick()方法,在這個方法中調用onArticleSelected()來與activity共享事件,如下:
public static class FragmentA extends ListFragment{
OnArticleSelectedListener mListener;
...
@Override
public void onListItemClick(ListView l,View v,int position,long id){
//Append the clicked item's row ID with the content provider Uri
Uri noteUri =ContentUris.withAppendedId(ArticleColumns.CONTENT_URI,id);
//Send the event and Uri to the host activity
mListener.onArticleSelected(noteUri);
}
...
}
onListItemClick()傳入的參數id是列表的被選中的行ID,另一個fragment用這個ID來從程序的ContentProvider中取得標題的內容。