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

Android TabLayout 使用方法詳解

編輯:關於 Android 程式設計

2015 年的 Google I/O 大會帶來了更完整的 Material Design 設計規範,同時也推出了全新的 Android Design Support Library。這個支援庫提供了更標準的 MD 風格控制項,而且相容性相當廣,可以直接向下相容到 Android 2.2。

本文以一個仿電商商品詳情頁的實作為例,記錄 TabLayout 的接入過程與踩到的坑。

先來看目標效果:

以下是實際做出來的樣子:

一、加入依賴

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.android.support:design:24.2.0'
    compile 'com.android.support:recyclerview-v7:24.2.0'
    compile 'com.android.support:cardview-v7:24.2.0'
}

二、Toolbar 與 TabLayout 的組合

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

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:gravity="center_vertical"
        app:navigationIcon="@drawable/back_icon" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="horizontal">

            <android.support.design.widget.TabLayout
                android:id="@+id/tabLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:background="@drawable/more_icon" />
    </android.support.v7.widget.Toolbar>

    <View />

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

這個版面裡最關鍵的一點,是 TabLayout 上的 app:tabMode="scrollable",它把 Tab 的模式設為可滑動。其他用法與常見的指示器(Indicator)大同小異:設定 Adapter,再讓資料驅動頁面。

三、撰寫 Adapter

public class ProductDetailPagerAdapter extends FragmentPagerAdapter {
    private List<String> mTitles;

    public ProductDetailPagerAdapter(FragmentManager fm, List<String> mTitles) {
        super(fm);
        this.mTitles = mTitles;
    }

    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
            return new ProductFragment();
        } else if (position == 1) {
            return new ProductDetailFragment();
        }
        return new ProductFragment();
    }

    @Override
    public int getCount() {
        return mTitles.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mTitles.get(position);
    }
}

四、頁面主要邏輯

public class ProductDetailsActivity extends BaseActivity {

    @BindView(R.id.viewPager) ViewPager viewPager;
    @BindView(R.id.tabLayout) TabLayout tabLayout;
    @BindView(R.id.toolbar)   Toolbar   toolbar;

    private TextView tabProduct;
    private TextView tabDetail;
    private List<String> mTitles = null;
    private ProductDetailPagerAdapter productPagerAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_details);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        initToolbar();
        initViewPager();
    }

    private void initToolbar() {
        setTitle("");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        initTab();
        initTabChange();
    }

    private void initTabChange() {
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
                switch (tab.getPosition()) {
                    case 0:
                        tabProduct.setTextColor(getResources().getColor(R.color.c8));
                        tabProduct.setTextSize(18);
                        break;
                    case 1:
                        tabDetail.setTextColor(getResources().getColor(R.color.c8));
                        tabDetail.setTextSize(18);
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                tabProduct.setTextColor(getResources().getColor(R.color.c7));
                tabDetail.setTextColor(getResources().getColor(R.color.c7));
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) { }
        });
    }

    private void initTab() {
        tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.c8));
        tabLayout.setSelectedTabIndicatorHeight(UIUtils.dp2px(this, 2));
        tabLayout.setTabTextColors(R.color.c7, R.color.c8);

        tabLayout.addTab(tabLayout.newTab()
                .setCustomView(R.layout.item_detail_tab_product_layout));
        tabProduct = (TextView) findViewById(R.id.tab_product);
        tabProduct.setTextColor(getResources().getColor(R.color.c8));

        tabLayout.addTab(tabLayout.newTab()
                .setCustomView(R.layout.item_detail_tab_detail_layout));
        tabDetail = (TextView) findViewById(R.id.tab_detail);
        tabProduct.setTextColor(getResources().getColor(R.color.c7));
    }

    private void initViewPager() {
        mTitles = new ArrayList<>();
        mTitles.add("商品");
        mTitles.add("詳情");

        productPagerAdapter = new ProductDetailPagerAdapter(
                getSupportFragmentManager(), mTitles);
        viewPager.setAdapter(productPagerAdapter);

        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                tabLayout.getTabAt(position).select();
            }
        });
    }

    public static void open(Context context) {
        Intent intent = new Intent(context, ProductDetailsActivity.class);
        context.startActivity(intent);
    }
}

五、該不該用 TabLayout

看到上面的程式碼,很多人會覺得麻煩——我也這麼認為。TabLayout 雖然可定制性高,但相比自己寫 ViewPager 加 Indicator,程式碼量並沒有真正減少,反而因為需要手動切換文字顏色與字級而多了不少樣板。

因此,如果設計稿的規格比較特殊,自訂控制項往往比硬套 TabLayout 更省事。TabLayout 真正划算的場景,是設計完全貼合 Material Design 規範的時候。

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