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

Android Fragment 的兩種用法:XML 靜態聲明與代碼動態加載

編輯:關於 Android 程式設計

Fragment 是 Android 3.0 之後引入的組件,目的是讓界面邏輯能夠復用到不同尺寸的屏幕上。實際開發中,Fragment 的用法大致可以歸成兩類:一種是在布局文件裡靜態聲明,一種是在代碼中動態添加。下面分別演示。

一、第一種:代碼動態添加

1. 主布局 activity_main.xml

在一個水平的 LinearLayout 中放兩個豎向容器,左邊放按鈕,右邊留空用來承載 Fragment。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/linerlayout1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#CCCCCC"
        android:orientation="vertical" >

        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="顯示窗口" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linerlayout2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:background="#CCFFDD"
        android:orientation="vertical" />
</LinearLayout>

2. Fragment 要加載的布局 right.xml

這個布局沒有特殊要求,放什麼控件取決於業務。示例裡放了一個 RatingBar 和一個 Button。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RatingBar
        android:id="@+id/ratingBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="點我試試" />
</LinearLayout>

3. MyFragment.java

繼承 Fragment 類,重點是重寫 onCreateView:在這裡 inflate 布局並完成控件初始化。

public class MyFragment extends Fragment {

    public MyFragment() { }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // R.layout.right 就是 Fragment 要展示的界面
        View view = inflater.inflate(R.layout.right, null);
        Button button = (Button) view.findViewById(R.id.button11);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "hello world!", Toast.LENGTH_LONG).show();
            }
        });
        return view;
    }

    @Override
    public void onPause() {
        super.onPause();
    }
}

注意 inflate 的第三個參數傳 null,因為 Fragment 會自己管理自己的視圖層級;同時 Toast 要用 getActivity() 而不是 getApplicationContext() 獲取 Context。

4. MainActivity.java

public class MainActivity extends Activity {

    private Button button;
    private FragmentManager fragmentManager;      // 用於管理 Fragment
    private FragmentTransaction fragmentTransaction; // 事務

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

        button = (Button) this.findViewById(R.id.button1);
        fragmentManager = getFragmentManager();

        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                fragmentTransaction = fragmentManager.beginTransaction();
                MyFragment myFragment = new MyFragment();
                // 第一個參數:放到哪個容器;第二個參數:要放入的 Fragment
                fragmentTransaction.add(R.id.linerlayout2, myFragment);
                fragmentTransaction.commit();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

效果是:點擊左側灰色區域的按鈕,右側出現 Fragment 的布局。

二、第二種:布局文件靜態聲明

項目結構與上面基本一致,區別在於直接在布局裡寫 fragment 標簽:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/fragment1"
        android:name="com.example.tablet_fragment_fragementmanager.MyFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="37dp" />
</RelativeLayout>

此時 MyFragment 只負責找到自己的布局即可,不做業務處理:

public class MyFragment extends Fragment {

    public MyFragment() { }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        /* 只需返回布局文件 */
        return inflater.inflate(R.layout.text, null);
    }

    @Override
    public void onResume() {
        super.onResume();
    }
}

業務邏輯則全部放在 Activity 裡。由於 Fragment 已經寫死在布局中,不需要 beginTransaction,直接用 FragmentManager 按 ID 找到它就行:

/*
 * 布局文件中拖入 fragment 後,用下面的方法找到特定的 fragment,
 * 不需要使用 beginTransaction
 */
public class MainActivity extends Activity {

    private MyFragment fragment;
    private FragmentManager fragmentManager;
    private Button button;

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

        fragmentManager = getFragmentManager();
        // 使用 ID 作為唯一標識符查找 Fragment
        fragment = (MyFragment) fragmentManager.findFragmentById(R.id.fragment1);
        // 也可以按 tag 查找:
        // fragment = (MyFragment) fragmentManager.findFragmentByTag("fragment1");

        button = (Button) fragment.getView().findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "hello world!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

三、兩種方式的取捨

靜態聲明(XML 中的 fragment 標簽)寫法簡單,但缺點很致命:一旦加入布局就無法在運行時替換或移除,也不方便接入返回棧。因此它只適合那些從頭到尾固定不變的界面塊。

動態添加(FragmentTransaction)靈活得多,可以配合 addToBackStack() 實現返回鍵逐層回退,也能隨時 replace、remove,是實際項目中的主流做法。官方後來推薦的 FragmentContainerView likewise 走的是動態路線。

一句話結論:學習階段兩種都該動手寫一遍,寫業務時預設選動態添加。

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