Android學習筆記2:Activity(二)—— Fragments

昨天貌似CSDN的博客登不上,所以沒更新,也順帶的休息了一天 O(∩_∩)O

 

今天我們來研究下Fragments,這個模塊貌似用的不多,因爲在好多書上都沒提及,不過官方放出來了,應該就有其用意,既然這個系列叫做“研習”,自然就不能忽略了。

該模塊使用版本最低爲Android3.0(API level 11)

Fragments翻譯的意思爲“片段”,官方給出的解釋爲"A Fragmemts represents a behavior or a portion of user interface in anActivity"。我們可以理解成他是組成Activity的一部分,他擁有自己獨立的生命週期(lifecycle)、事件(events)。

雖然Fragments擁有自己的生命週期,但它的生命週期還制約與它所嵌入的Activity,如果Activity銷燬了,那Fragments也就不存在了。

 

Frgments適用於平板電腦(貌似3.0就是爲tablet而生的),其目的是爲了在一個屏幕內看到更多的信息,就好比網頁中的兩列布局,點擊左側的菜單,在右側展示新的內容,見下圖

 

創建Fragment

創建一個Fragment,需要建立一個該類繼承Fragment類的子類和一個佈局文件

public static class ExampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.example_fragment, container, false);
    }
}

在onCreateView()方法中設置Fragment的佈局文件。

當然除了繼承Fragment類,還能繼承DialogFragment、ListFragment和PreferenceFragment類,這三個類也都繼承了Fragment類

 

在Activity中加入Fragment

在Activity中加入Fragment最方便的方法,就是在Activity佈局文件中直接加入Fragment的佈局文件,下面就是一個例子

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment android:name="com.example.news.ArticleListFragment"
            android:id="@+id/list"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
    <fragment android:name="com.example.news.ArticleReaderFragment"
            android:id="@+id/viewer"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
</LinearLayout>


Fragment的生命週期

Fragment的生命週期其實和Activity差不多,以下是官方提供的一張對比圖

 

其實Fragment的內容官方給的還是挺多的,最後也給了個例子。本來想寫的詳細,但覺得那好像在翻譯文章,但想言簡意賅,貌似又初寫博文,沒那水平,所以就將就着寫點重點和心得。以後有了更深入的理解再補充……

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章