compile 'com.android.support:design:23.1.1'
compile 'com.android.support:support-v4:23.1.1'

tabLayout一般结合viewPager使用

setupWithViewPager的调用要放置在viewPager.setAdapter后面 (viewPagerAdapter继承于FragmentPagerAdapter)

    viewPager.setAdapter(viewPagerAdapter);  
    tabLayout.setupWithViewPager(viewPager);  

xml示例:

 <!--
     tabIndicatorColor属性为标签底部下滑线颜色
     tabTextColor为标签未选中时字体颜色
     tabSelectedTextColor为选中时字体颜色

     app:tabMode有两个值:fixed和scrollable。
     app:tabGravity有两个值:fill和center。
 -->
 <android.support.design.widget.TabLayout  
    android:id="@+id/tab_layout"  
    android:layout_width="match_parent"  
    app:tabIndicatorColor="@android:color/holo_blue_light"  
    app:tabTextColor="@android:color/darker_gray"  
    app:tabSelectedTextColor="@android:color/black"  
    android:layout_height="wrap_content"
    style="@style/MyCustomTabLayout" /> 

TabLayout每个标签的文字会有 viewPagerAdapter的public CharSequence getPageTitle(int position)提供,无需另外添加,只要实现viewPagerAdapter的public CharSequence getPageTitle(int position)即可

还可以自定义style

<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
        <item name="tabMaxWidth">@dimen/tab_max_width</item>
        <item name="tabIndicatorColor">?attr/colorAccent</item>
        <item name="tabIndicatorHeight">0dp</item>
        <item name="tabPaddingStart">12dp</item>
        <item name="tabPaddingEnd">12dp</item>
        <item name="tabBackground">@color/tab_bgcolor</item>
        <item name="tabSelectedTextColor">?android:textColorPrimary</item>
</style>

还可以设置icon

TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setIcon(getResources().getDrawable(R.mipmap.ic_launcher));

另外还可以自定义tab的view

for (int i = 0; i < tabLayout.getTabCount(); i++) {
    TabLayout.Tab tab = tabLayout.getTabAt(i);
    if (tab != null) {
        tab.setCustomView(pagerAdapter.getTabView(i));
    }
}

设置监听事件

mTablayout.setOnTabSelectedListener

标签: none

评论已关闭