Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Fragment 靜態加載完整示例

編輯:關於 Android 程式設計

一、Fragment 知識概要

Android 3.0 引入了 Fragment,主要目的是適配大屏幕設備,支持更動態、更靈活的 UI 設計。Fragment 應當被視為一個模塊化、可重用的組件:它定義了自己的布局,並透過一組生命周期回調定義了自己的行為,因此可以被打包進多個 Activity 中使用。

(1)Fragment 可以作為 Activity 界面的一部分出現;

(2)一個 Activity 中可同時存在多個 Fragment,同一個 Fragment 也能被多個 Activity 複用;

(3)Activity 運行期間,可以動態添加、移除或替換 Fragment;

(4)Fragment 能響應自己的輸入事件,有自己的生命周期,但受宿主 Activity 的生命周期影響;

(5)Fragment 第一次繪製界面時系統調用 onCreateView(),該方法返回一個 View(不顯示 UI 時返回 null)。

Fragment 的加載方式有兩種:靜態加載與動態加載。本文先講靜態加載。

二、準備階段

後續會用同一個 App 串起 Fragment 的各項知識,整體布局是上方內容區 + 底部四個 Tab 按鈕:

在 values 下新增 color.xml:

<resources>
    <color name="gray">#88000000</color>
    <color name="white">#ffffff</color>
</resources>

在 drawable 下新增 radio_pressed.xml,用於 Tab 的選中態:

<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@color/gray"  android:state_checked="true" />
    <item android:drawable="@color/white" android:state_pressed="true" />
    <item android:drawable="@color/white" />
</selector>

主布局 main.xml:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" />

    <RadioGroup
        android:id="@+id/radiogroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:gravity="center_horizontal"
        android:orientation="horizontal">

        <RadioButton android:id="@+id/first"
            android:layout_width="0dp" android:layout_height="wrap_content"
            android:layout_weight="1" android:button="@null"
            android:background="@drawable/radio_pressed"
            android:drawableTop="@drawable/ic_launcher"
            android:gravity="center_horizontal" android:text="靜態加載" />
        <!-- second / thrid / fourth 分別對應 動態加載、生命周期、傳值通信 -->
    </RadioGroup>
</RelativeLayout>

MainActivity 中加載佈局並監聽 Tab 切換:

public class MainActivity extends Activity implements RadioGroup.OnCheckedChangeListener {
    private RadioGroup group;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        group = (RadioGroup) findViewById(R.id.radiogroup);
        group.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.first:  /* 靜態加載 */ break;
            case R.id.second: /* 動態加載 */ break;
            case R.id.thrid:  /* 生命周期 */ break;
            case R.id.fourth: /* 傳值通信 */ break;
        }
    }
}

三、靜態加載

靜態加載的做法是:直接在 Activity 的佈局文件裡用 <fragment> 標籤聲明 Fragment。有兩個細節要特別注意:

· android:name 必須指定要在佈局中實例化的 Fragment 類的完整包名;

· 靜態加載時必須提供唯一標識,可以用 android:id,也可以用 android:tag。

1. Fragment 自己的佈局 fragment.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="我的Fragment" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

2. MyFragment 類並加載上述佈局

public class MyFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 把 layout 佈局文件轉換成 View 對象
        View view = inflater.inflate(R.layout.fragment, container, false);

        TextView text = (TextView) view.findViewById(R.id.text);
        Button button = (Button) view.findViewById(R.id.button);
        text.setText("靜態加載Fragment");
        button.setText("獲取內容");

        button.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) { /* TODO */ }
        });
        return view;
    }
}

這裡的 inflate(resource, root, attachToRoot) 三個參數含義:resource 是 Fragment 要加載的佈局,root 是父容器,attachToRoot 傳 false 表示暫不把新 View 掛到父容器上,由 Fragment 框架自己處理。

3. 宿主佈局 jingtai.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <!-- 靜態加載必須指定一個 id;name 要寫完整包名 -->
    <fragment
        android:id="@+id/fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:name="com.example.fragment.MyFragment" />
</LinearLayout>

4. JingTaiActivity

public class JingTaiActivity extends Activity {
    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jingtai);

        Button button = (Button) findViewById(R.id.button);
        tv = (TextView) findViewById(R.id.text);

        button.setText("改變");
        button.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                tv.setText("TextView改變了");
            }
        });
    }
}

5. 在 MainActivity 中跳轉

case R.id.first:
    startActivity(new Intent(MainActivity.this, JingTaiActivity.class));
    break;

關鍵結論

MainActivity 跳到 JingTaiActivity,後者加載了 jingtai.xml,其中用 <fragment> 引入 com.example.fragment.MyFragment,而 MyFragment 內部又有自己的 text 和 button。回到 JingTaiActivity 後,可以直接通過 findViewById 訪問 Fragment 佈局中的 text 和 button。

也就是說,當 Fragment 以靜態方式加載進 Activity 後,Fragment 內部的控件對 Activity 是共享可見的。這帶來了便利,也埋下了耦合的隱患——靜態加載的 Fragment 生命週期完全跟隨宿主,適合寫死在佈局裡的固定模塊;若需要運行時增刪替換,就應該改用動態加載。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved