android Fragments詳解五:與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的事件

  有時,你可能需要fragmentactivity共享事件。一個好辦法是在fragment中定義一個回調接口,然后在activity中實現之。

  例如,還是那個新聞程序的例子,它有一個activityactivity中含有兩個fragmentfragmentA顯示新聞標題,fragmentB顯示標題對應的內容。fragmentA必須在用戶選擇了某個標題時告訴activity,然后activity再告訴fragmentBfragmentB就顯示出對應的內容(為什么這么麻煩?直接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,每次選中列表的一項時,就會調用fragmentAonListItemClick()方法,在這個方法中調用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中取得標題的內容。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM