Android中TabLayout和ViewPager的结合使用

首先在AndroidStudio中引入这样一个包

compile ‘com.android.support:design:23.1.1’

com.Android.support:design:23.1.1支持的新控件。

android.support.design.widget.TextInputLayout 强大带提示的MD风格的EditText
android.support.design.widget.FloatingActionButton MD风格的圆形按钮,来自于ImageView
android.support.design.widget.Snackbar 类似Toast,添加了简单的单个Action
android.support.design.widget.TabLayout 选项卡
android.support.design.widget.NavigationView DrawerLayout的SlideMenu
android.support.design.widget.CoordinatorLayout 超级FrameLayout
android.support.design.widget.AppBarLayout MD风格的滑动Layout
android.support.design.widget.CollapsingToolbarLayout 可折叠MD风格ToolbarLayout
详细说明请看

http://www.open-open.com/lib/view/open1433385856119.html

布局图如下 上面是tablayout 下面是viewpager就好了

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#34CE7B"
            app:tabIndicatorColor="@android:color/white"
            app:tabSelectedTextColor="@android:color/white"
            app:tabTextAppearance="@style/style_tab_text_size"
            app:tabTextColor="@android:color/white">
        android.support.design.widget.TabLayout>
    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    android.support.v4.view.ViewPager>

LinearLayout>

初始化Tablayout以及添加title数据

//初始化title的名称 可以在Values/arrays.xml中定义

mTitleList=new ArrayList<>();
mTitleList.add(getResources().getString(R.string.hot_scenic));
mTitleList.add(getResources().getString(R.string.newest_scenic));

//设置Tab_Layout的样式
mTabLayout.setTabMode(TabLayout.MODE_FIXED);
//为tablayout添加tab名称
if(mTitleList!=null){
    mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(0)));
    mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(1)));
}

最后viewpager设置好fragmentPagerAdapter之后再将viewpager和tablayout关联起来,还要在fragmentPagerAdapter中实现下面方法才显示Title

@Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }

最后
mTabLayout.setupWithViewPager(mViewPager);

你可能感兴趣的:(随笔)