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

Android Fragment 實作入門:主從式清單與詳情頁連動

編輯:關於 Android 程式設計

Fragment 自 Android 3.0 起被正式引入,它本質上是一段「可以被塞進 Activity 裡的模組化介面」。它有自己的生命週期、自己的視圖層級,也能透過 FragmentManager 被動態替換。最典型的應用場景就是主從結構:左邊是清單,右邊是對應的詳情。

一、先寫一個可接收參數的詳情 Fragment

Fragment 不建議用建構子帶參數,官方推薦的做法是透過 Bundle 搭配靜態的 newInstance() 工廠方法。這樣做的好處是,當系統因記憶體回收而重建 Fragment 時,參數能跟著實例一起被保存與還原。

public class DetailsFragment extends Fragment {

    private static final String[] WEEKS = {"a-1", "b-1", "c-1"};

    public static DetailsFragment newInstance(int index) {
        DetailsFragment fragment = new DetailsFragment();
        Bundle args = new Bundle();
        args.putInt("index", index);
        fragment.setArguments(args);
        return fragment;
    }

    public int getShowIndex() {
        return getArguments().getInt("index", 0);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        TextView text = new TextView(getActivity());
        text.setText(WEEKS[getShowIndex()]);
        return text;
    }
}

二、用 ListFragment 承接清單與點擊事件

清單這一端直接繼承 ListFragment,省下自己找 ListView、設定 Adapter 的力氣。這裡刻意選用 simple_list_item_activated_1 這個系統版面配置,因為它自帶「已選取」狀態的高亮效果,正好符合主從互動的視覺需求。

public class FragmentAcitivity extends ListFragment {

    private static final String[] WEEKS = {"a", "b", "c"};

    // 目前選取的位置
    private int mCurCheckPosition = 0;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_activated_1,
                android.R.id.text1, WEEKS));

        // 建立當下就先顯示預設項目的詳情
        showDetails(mCurCheckPosition);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        showDetails(position);
    }

    /**
     * 依選取的行號切換詳情區塊
     */
    public void showDetails(int index) {
        FragmentManager fm = getFragmentManager();
        DetailsFragment details = (DetailsFragment) fm.findFragmentById(R.id.details);

        // 只有當目前顯示的內容跟請求的內容不同時才重建
        if (details == null || details.getShowIndex() != index) {
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            getListView().setItemChecked(index, true);

            details = DetailsFragment.newInstance(index);

            FragmentTransaction ft = fm.beginTransaction();
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            // replace 會整塊換掉;若改用 add 則會不斷往容器裡疊
            ft.replace(R.id.details, details);
            ft.commit();
        }
    }
}

這裡有兩個關鍵細節值得留意。第一,setChoiceMode(CHOICE_MODE_SINGLE) 搭配 setItemChecked() 才能讓清單呈現單選效果。第二,replace() 與 add() 的差異在於前者會移除容器中原本的 Fragment,後者則是往上疊加,做切換式介面時幾乎都該用 replace()。

三、版面配置:靜態宣告與動態容器並存

<?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="horizontal" >

    <fragment
        android:id="@+id/titles"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        class="com.example.fragment.FragmentAcitivity" />

    <FrameLayout
        android:id="@+id/details"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:background="?android:attr/detailsElementBackground" />

</LinearLayout>

左半部用 <fragment> 標籤直接寫死,這叫靜態宣告:Fragment 會在 Activity 建立時就一起被實例化,生命週期與宿主綁死。右半部只放一個空的 FrameLayout 當容器,內容由程式碼在執行期透過 FragmentTransaction 塞進去,這叫動態載入。兩者並用,就是最經典的「列表固定、詳情可換」組合。

四、平板與手機的延伸思考

如果目標裝置包含平板,通常會再往下走一步:在 res/layout 放單欄配置、在 res/layout-sw600dp 放雙欄配置,並在程式碼中判斷 R.id.details 是否存在,來決定是「換 Fragment」還是「開新 Activity」。Fragment 真正的價值就在這裡——同一套邏輯,兩種形態,不必寫兩份程式。

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