Android Fragment實踐

介紹

Fragment 的出現一方面是為了緩解 Activity 任務過重的問題,另一方面是為了處理在不同屏幕上 UI 組件的布局問題。
Fragment 擁有和 Activity 一致的生命周期,它和 Activity 一樣被定義為 Controller 層的類。 它將屏幕分解為多個「Fragment(碎片)」,但它又不同于 View,它干的實質上就是 Activity 的事情,負責控制 View 以及它們之間的邏輯。
將屏幕碎片化為多個 Fragment 后,其實 Activity 只需要花精力去管理當前屏幕內應該顯示哪些 Fragments,這是一種組件化的思維。

封裝BaseFragment基類

/**
  * Fragment基類
  * Created by XP on 2016/1/9.
  */
public abstract class BaseFragment extends Fragment {

protected abstract void initViews();

protected abstract int provideLayoutId();

protected View rootView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(provideLayoutId(), container, false);
    ButterKnife.bind(this, rootView);
    initViews();
    return rootView;
   }
}

使用靜態工廠方法newInstance(...)來獲取Fragment實例

public static Communication newInstance(String s) {
    Communication communication = new Communication();
    Bundle bundle = new Bundle();
    bundle.putString("type", s);
    communication.setArguments(bundle);
    return communication;
}

避免錯誤操作導致Fragment的視圖重疊

在add或者replace的時候,調用含有TAG參數的那個方法,之后再add相同TAG的Fragment的話,之前的會被替換掉,也就不會同時出現多個相同的Fragment了。

判斷一個頁面該使用Fragment還是Activity

如果后一個頁面不需要用到前一個頁面的太多數據,推薦用Activity展示,否則最好用Fragment( 當然這也不是絕對的)。例如SplashActivity和MainActivity沒有太多的耦合度,此時可以分成兩個Activity。

Fragment的通信

在Fragment中調用Activity中的方法

Fragment可以通過·getActivity()·方法來獲得Activity的實例,然后就可以調用一些Activity的方法。

在Activity中調用Fragment中的方法

activity也可以獲得一個fragment的引用,從而調用fragment中的方法。獲得fragment的引用要用FragmentManager,之后可以調用findFragmentById() 或者 findFragmentByTag()。

Fragment與Fragment之間的通信

首先在一個Fragment中可以得到與它相關聯的Activity,然后再通過這個Activity去獲取另外一個Fragment的實例,這樣就實現了不同Fragment之間的通信。

接口回調

可以在Fragment類中定義一個接口,并在它所屬的Activity中實現該接口。Fragment在它的onAttach()方法執行期間捕獲該接口的實現,然后就可以調用接口方法,以便跟Activity通信。

參考:
https://www.zhihu.com/question/39662488
https://www.zhihu.com/question/38100871
http://www.cnblogs.com/smyhvae/p/4000390.html

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容