Android Fragment詳解(五):Fragment與Activity通訊
與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
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中取得標題的內容。