TabLayout

一、什麼是TabLayout
1.以前使用TabHost。比如網易新聞客戶端那樣可以滑動的標題欄。
android.support.design.widget.TabLayout

使用場景:
TabLayout控件,切換Fragment
TabLayout+ViewPager+Fragment

二、使用

1.引入Design兼容包
2.佈局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.seasons.live.tablayout.TabLayoutActivity" >

    <android.support.design.widget.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        app:tabGravity="fill"
        app:tabIndicatorColor="@color/colorPrimary_pink"
        app:tabMode="scrollable"
        app:tabSelectedTextColor="@color/colorPrimary_pinkDark"
        app:tabTextColor="@color/colorPrimary_pink" />

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

</LinearLayout>

屬性:

app:tabIndicatorColor="@color/colorPrimary_pink"//指示器的顏色
app:tabTextColor="@color/colorPrimary_pink"//tab的文字顏色
app:tabSelectedTextColor="@color/colorPrimary_pinkDark"//選中的tab的文字顏色
app:tabMode="fixed"//scrollable:可滑動;fixed:不能滑動,平分tabLayout寬度
app:tabGravity="center"// fill:tabs平均填充整個寬度;center:tab居中顯示

3.activity

final ViewPager viewPager = (ViewPager) findViewById(R.id.vp);
        tabLayout = (TabLayout) findViewById(R.id.tablayout);
        MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
        // 1.TabLayout和Viewpager關聯
        tabLayout.setOnTabSelectedListener(new OnTabSelectedListener() {

            @Override
            public void onTabUnselected(Tab arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onTabSelected(Tab tab) {
                // 被選中的時候回調
                viewPager.setCurrentItem(tab.getPosition(), true);
            }

            @Override
            public void onTabReselected(Tab arg0) {
                // TODO Auto-generated method stub

            }
        });
        // 2.ViewPager滑動關聯tabLayout
        viewPager
                .addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(
                        tabLayout));

        // 設置tabLayout的標籤來自於PagerAdapter
        tabLayout.setTabsFromPagerAdapter(adapter);

        viewPager.setAdapter(adapter);
    }

三、如何將TabLayout實現成底部導航的樣子?
1.就把TabLayout放在佈局底部
2.如何去掉底部的indicator,可以app:tabIndicatorHeight=”0dp”
3.實現自己的效果,比如
微信:設置自定義的標籤佈局
Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(view);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章