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

Android 滾動 Tab 實作:用 ViewPager 加 Fragment 打造可滑動分頁

編輯:關於 Android 程式設計

先來看成果:一個可以左右滑動切換的分頁介面,每個分頁有自己的標題與內容,最後一頁還能放上一個與前幾頁不同樣式的「關於我」頁面。

如果你對這個效果有興趣,別被篇幅嚇到,其實原理並不複雜,關鍵是 android-support-v4.jar 提供的 ViewPager 與 Fragment 支援。

主布局 activity_main.xml

整個畫面就是一個 ViewPager,作為承載各分頁的容器:

<android.support.v4.view.ViewPager xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
</android.support.v4.view.ViewPager>

主 Activity

核心只有一件事:給 mViewPager 設定一個 Adapter,也就是我們自訂的 FragmentAdapter。

public class MainActivity extends FragmentActivity {
    private FragmentAdapter mFragmentAdapter;
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mFragmentAdapter = new FragmentAdapter(MainActivity.this, getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mFragmentAdapter);
    }

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

FragmentAdapter 的實作

這個 Adapter 繼承自 FragmentPagerAdapter,透過 getItem 決定每個位置要放哪個 Fragment,getCount 決定總頁數,getPageTitle 決定分頁標題:

public class FragmentAdapter extends FragmentPagerAdapter {
    private Context mContext;

    public FragmentAdapter(Context context, FragmentManager fm) {
        super(fm);
        mContext = context;
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment;
        if (position == 2) {
            fragment = new AboutMeFragment();
        } else {
            fragment = new TabFragment();
            Bundle args = new Bundle();
            args.putInt(TabFragment.TAB_POSITION, position + 1);
            fragment.setArguments(args);
        }
        return fragment;
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        if (position == 2) {
            return mContext.getString(R.string.about_me_title);
        } else {
            Locale l = Locale.getDefault();
            return mContext.getString(R.string.tab_fragment_title, position + 1).toUpperCase(l);
        }
    }
}

這裡刻意設計了兩種 Fragment:當 position 等於 2(也就是最後一頁)時,回傳 AboutMeFragment,其餘位置則回傳 TabFragment,並透過 Bundle 把頁碼位置傳進去。這說明了同一個 Adapter 完全可以混搭不同類型的 Fragment,彈性很高。

TabFragment

它的布局只有一個 TextView,重點在於用 getArguments() 取出傳入的頁碼,動態設定顯示文字:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.lichen.remind.R;

public class TabFragment extends Fragment {
    public static final String TAB_POSITION = "tab_position";

    public TabFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_tab, container, false);
        TextView tabLabel = (TextView) rootView.findViewById(R.id.tab_label);
        tabLabel.setText(getString(R.string.tab_fragment_content, getArguments().getInt(TAB_POSITION)));
        return rootView;
    }
}

AboutMeFragment 與其布局

AboutMeFragment 的布局同樣是一個 TextView,但用了 android:drawableTop 屬性在文字上方加上一個圖示:

<?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:gravity="center_horizontal|center_vertical"
    android:orientation="vertical" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableTop="@drawable/me"
        android:text="@string/about_me_email"/>
</LinearLayout>
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.lichen.remind.R;

public class AboutMeFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_about_me, container, false);
        return rootView;
    }
}

字串資源的佔位符技巧

strings.xml 這裡用了帶參數的佔位寫法,讓同一段文字能依頁碼動態替換,搭配 xliff 命名空間即可帶入數值:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="app_name">Remind</string>
    <string name="action_settings">Settings</string>
    <string name="about_me_title">關於我</string>
    <string name="about_me_email">chain_li7@163.com</string>
    <string name="tab_fragment_title">第 <xliff:gid="tab_fragment_title_position">%1$d</xliff:g> 個Tab</string>
    <string name="tab_fragment_content">這是第 <xliff:gid="tab_fragment_content_position">%1$d</xliff:g> 個Tab頁面</string>
</resources>

整體來說,滾動 Tab 的骨架就是「ViewPager + FragmentPagerAdapter」,剩下就看你如何設計每個 Fragment 的內容與樣式。

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