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

Android 嵌套 Fragment 實戰:FrameLayout 外層切模塊、ViewPager 內層切頁籤

編輯:關於 Android 程式設計

前言

之前介紹 ActivityGroup 時,不少人問到嵌套使用的問題。同樣的需求在 Fragment 上自然也會出現,好消息是當時最新的 Android support 套件已經支援這個特性。這裡就跳過 Fragment 基礎介紹,另外要提醒的是 TabActivity 早已被標記為 deprecated。

正文

一、準備

最新 Android 相容套件的說明請見官網,實際檔案可以在 Android SDK 目錄下的 extras/android/support/v13/android-support-v13.jar 找到,注意它是伴隨 Android 4.2 一起更新的版本。關於嵌套 Fragment 的官方說明也建議先讀過再動手。

二、效果截圖

三、程式碼

FragmentNestActivity.java

public class FragmentNestActivity extends FragmentActivity implements OnClickListener {

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.nested_fragments);
        findViewById(R.id.btnModule1).setOnClickListener(this);
        findViewById(R.id.btnModule2).setOnClickListener(this);
        findViewById(R.id.btnModule3).setOnClickListener(this);
        findViewById(R.id.btnModule1).performClick();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnModule1:
                addFragmentToStack(FragmentParent.newInstance(0));
                break;
            case R.id.btnModule2:
                addFragmentToStack(FragmentParent.newInstance(1));
                break;
            case R.id.btnModule3:
                addFragmentToStack(FragmentParent.newInstance(2));
                break;
        }
    }

    private void addFragmentToStack(Fragment fragment) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        // ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_in_left);
        ft.replace(R.id.fragment_container, fragment);
        ft.commit();
    }

    /** 嵌套 Fragment */
    public final static class FragmentParent extends Fragment {

        public static final FragmentParent newInstance(int position) {
            FragmentParent f = new FragmentParent();
            Bundle args = new Bundle(2);
            args.putInt("position", position);
            f.setArguments(args);
            return f;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View convertView = inflater.inflate(R.layout.viewpager_fragments, container, false);
            ViewPager pager = (ViewPager) convertView.findViewById(R.id.pager);
            final int parent_position = getArguments().getInt("position");

            // 關鍵:這裡用的是 getChildFragmentManager()
            pager.setAdapter(new FragmentStatePagerAdapter(getChildFragmentManager()) {
                @Override
                public Fragment getItem(final int position) {
                    return new Fragment() {
                        @Override
                        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                                 Bundle savedInstanceState) {
                            TextView convertView = new TextView(getActivity());
                            convertView.setLayoutParams(new ViewGroup.LayoutParams(
                                    ViewGroup.LayoutParams.FILL_PARENT,
                                    ViewGroup.LayoutParams.FILL_PARENT));
                            convertView.setGravity(Gravity.CENTER);
                            convertView.setTextSize(30);
                            convertView.setTextColor(Color.BLACK);
                            convertView.setText("Page " + position);
                            return convertView;
                        }
                    };
                }

                @Override
                public int getCount() {
                    return 3;
                }

                @Override
                public CharSequence getPageTitle(int position) {
                    return "Page " + parent_position + " - " + position;
                }
            });
            return convertView;
        }
    }
}

程式碼說明

整段程式碼裡最關鍵的,就是 getChildFragmentManager() 的支援。如果這裡誤用了 getSupportFragmentManager(),嵌套就會出問題。另外這段也示範了把 Fragment 寫成內部靜態類別的用法,newInstance 搭配 Bundle 傳參數是比較正規的做法,因為系統重建立 Fragment 時會走無參數建構子。

nested_fragments.xml

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

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1.0"
        android:background="#F7F5DE" >
    </FrameLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="@android:color/black"
        android:orientation="horizontal" >
        <ImageView android:id="@+id/btnModule1" ... />
        <ImageView android:id="@+id/btnModule2" ... />
        <ImageView android:id="@+id/btnModule3" ... />
    </LinearLayout>
</LinearLayout>

viewpager_fragments.xml

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

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <android.support.v4.view.PagerTitleStrip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top" />
    </android.support.v4.view.ViewPager>
</LinearLayout>

程式碼說明

注意!實測發現 ViewPager 並不適合當最外層容器,否則會報錯,這也是為什麼外層要用 FrameLayout 而不是直接放 ViewPager。

四、結構小結

這是一個相當典型的嵌套 Fragment 架構:最外層用 FrameLayout 負責幾大模塊之間的切換,內層再用 ViewPager 處理子模塊的滑動切換,兩層職責分明,實務上非常實用。

結語

我在考慮把 Support Package revision 11 的更新說明翻譯出來。總之強烈建議大家把相容套件升到最新版,很多嵌套相關的問題都是靠它解決的。

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