2015年5月29日 星期五

Android 開發 (九十六) What's New in M support-design-widget TabLayout

先讓我們看一下圖



在TabLayout出來之前,如果要做出類似的功能,除了自己刻之外,我想大部份的人都會利用https://github.com/astuetz/PagerSlidingTabStrip這個library吧

這個TabLayout 讓我們可以使用官方的api 而不用再依照3-party lib,不用再擔心library不再維護的問題了XD

接下來介紹該如何實做

跟正常的viewpager and tab一樣必須定義這兩個layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

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

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

接下來只需要initViewpager
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

然後再使用 setupWithViewPager 將viewpager set 進去就行了,
這邊有一個設定要特別注意, setTabMode 有分 MODE_FIX and MODE_SCROLLABLE
其中如果使用MODE_SCROLLABLE  tab的textview的寬度才會正常顯示,否則textview的寬度會只有一個字的寬度

如上圖所示

不過在使用這個api的時候有遇到一個問題,當我利用下面的程式碼
tabLayout.setTabTextColors(Color.BLUE,Color.parseColor("#FF2750"));
想要更換tab的顏色時,卻無法正確更換,
當然還有下面那條線的顏色,目前還找不到更換的方法,
我猜測只能由theme來更換了. 如果有試出來再跟大家分享囉

沒有留言:

張貼留言