Android - Fragment

一些優秀博客:
 
Fragment生命週期
              
onAttached() —— 當fragment被加入到activity時調用(在這個方法中能夠得到所在的activity)。
onCreateView() —— 當activity要獲得fragment的layout時,調用此方法,fragment在其中建立本身的layout(界面)。
onActivityCreated() —— 當activity的onCreated()方法返回後調用此方法
onDestroyView() —— 當fragment中的視圖被移除的時候,調用這個方法。
onDetach() —— 當fragment和activity分離的時候,調用這個方法。
 

Fragment與Activity
Fragment獲取Activity實例 Activity獲取Fragment實例
getActivtiy() getFragmentManager()>>
FragmentManager:
findFragmentById() 
findFragmentByTag()
popBackStack():將Fragment從後臺棧中彈出(模擬用戶按下BACK按鍵)
beginTransaction()>>
FragmentTransAction
add(int containerViewId, Fragment fragment
remove(R.id.framework,fragment ) addToBackStack() 
commit()
 
  1. //Activity中
  2. Fragment fragment =newFragment();
  3. FragmentManager fragmentManager = getFragmentManager();
  4. FragmentTransaction transaction =fragmentManager.beginTransaction();
  5. transaction.replace(R.id.framework,fragment);
  6. transaction.addToBackStack();
  7. transaction.commit();
 
Fragment與Activity相互通訊
Activity向Fragment傳遞數據
在Activity中建立Bundle數據包,並調用Fragment的setArguments(Bundle)便可將數據傳到Fragment

 
Fragment向Activity傳遞數據/Activity須要在Fragment運行中進行實時通訊:
在Fragment中定義一個內部回調接口,再讓包含該Activity的Activity實現該回調接口(可經過接口方法在Fragment運行中與其進行實時通訊),這樣Fragment便可調用該接口方法將數據傳回給Activity
 
例子
  1. //MainActivity
  2. publicclassMainActivityextendsActivityimplements BookFragment.Callbacks
  3. {
  4.     @Override
  5.     publicvoid onCreate(Bundle savedInstanceState)
  6.     {
  7.         super.onCreate(savedInstanceState);
  8.         setContentView(R.layout.activity_book_twopane);
  9.         // 建立Bundle,準備向Fragment傳入參數
  10.         Bundle arguments =newBundle();
  11.         arguments.putInt("name", x);
  12.         BookFragment fragment =newBookFragment();
  13.         fragment.setArguments(arguments);
  14.      getFragmentManager().beginTransaction()
                    .replace(R.id.book_detail_container, fragment)
                    .commit();
  15.     }
  16.     // 實現Callbacks接口必須實現的方法
  17.     @Override
  18.     publicvoid someAction(string s)
  19.     {
  20.         String s1=s;//獲取到fragment傳來的參數
  21.     }
  22. }
 
  1. //activity_book_twopane.xml
  2. <LinearLayout
  3.     xmlns:android="http://schemas.android.com/apk/res/android"
  4.     android:orientation="horizontal"
  5.     android:layout_width="match_parent"
  6.     android:layout_height="match_parent"
  7.     android:layout_marginLeft="16dp"
  8.     android:layout_marginRight="16dp"
  9.     android:divider="?android:attr/dividerHorizontal"
  10.     android:showDividers="middle">
  11.     <!-- 添加一個Fragment -->
  12.     <fragment
  13.         android:name="org.crazyit.app.BookFragment"
  14.         android:id="@+id/book_list"
  15.         android:layout_width="0dp"
  16.         android:layout_height="match_parent"
  17.         android:layout_weight="1"/>
  18.     <!-- 添加一個FrameLayout容器 -->
  19.     <FrameLayout
  20.         android:id="@+id/book_detail_container"
  21.         android:layout_width="0dp"
  22.         android:layout_height="match_parent"
  23.         android:layout_weight="3"/>
  24. </LinearLayout>
 
  1. //BookFragment
  2. publicclassBookFragment extends Fragment
  3. {
  4. privateCallbacks mCallbacks;
  5.         // 定義一個回調接口,該Fragment所在Activity須要實現該接口,該Fragment將經過該接口與它所在的Activity交互
  6. public interface Callbacks
  7. {
  8. publicvoid someAction(String s);
  9. }
  10. @Override
  11. publicvoid onCreate(Bundle savedInstanceState)
  12. {
  13. super.onCreate(savedInstanceState);
  14. }
  15.         @Override
  16.         publicView onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
  17.         {
  18.         View rootView = inflater.inflate(R.layout.fragment1,container,false);
  19.                   TextView tv= ((TextView) rootView.findViewById(R.id.book_title));
  20.                    tv.setText("");
  21.                    return rootView;
  22.         }
  23. @Override
  24. publicvoid onAttach(Activity activity)
  25. {
  26. super.onAttach(activity);
  27. // 若是Activity沒有實現Callbacks接口,拋出異常
  28. if(!(activity instanceof Callbacks))
  29. {
  30. thrownewIllegalStateException(
  31. "BookListFragment所在的Activity必須實現Callbacks接口!");
  32. }
  33. // 把該Activity當成Callbacks對象
  34. mCallbacks =(Callbacks)activity;
  35.      String s ="to activity";
  36.        mCallbacks.someAction(s);
  37. }
  38. @Override
  39. publicvoid onDetach()
  40. {
  41. super.onDetach();
  42. // 將mCallbacks賦爲null。
  43. mCallbacks = null;
  44. }
  45. }
 
  1. //fragment1.xml
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:layout_width="match_parent"
  4.     android:layout_height="match_parent"
  5.     android:orientation="vertical">
  6.   
  7.     <TextView
  8.         style="?android:attr/textAppearanceLarge"
  9.         android:id="@+id/book_title"
  10.         android:layout_width="match_parent"
  11.         android:layout_height="wrap_content"
  12.         android:padding="16dp"/>
  13.     
  14. </LinearLayout>

Fragment : onActivityResult(int requestCode, int resultCode, Intent intent) not be called in fragment
 
Option 1 :
If you're calling startActivityForResult() from the fragment then you should call startActivityForResult() not getActivity().startActivityForResult(), as it will result in fragment onActivityResult().
 
If you're not sure where you're calling on startActivityForResult() and how you will be calling methods.
Option 2:
Since Activity gets the result of onActivityResult(), you will need to override the activity's onActivityResult() and call super.onActivityResult() to propagate to the respective fragment for unhandled results codes or for all.
 

Fragment設計邏輯
 
 
 
 
 
 
 
 
 



相關文章
相關標籤/搜索