效果图:
代码:
布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?android:actionBarSize"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:background="@color/colorPrimary">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
app:tabMode="scrollable"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
MainActivity
//获取Tab名
mTitles = getResources().getStringArray(R.array.main_titles);
//viewPager设置适配器
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager(),mTitles));
//关联viewpager
tabLayout.setupWithViewPager(viewPager);
在res/values下创建arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="main_titles">
<item>首页</item>
<item>应用</item>
<item>游戏</item>
<item>专题</item>
<item>推荐</item>
<item>分类</item>
<item>热门</item>
</string-array>
</resources>
ViewPagerAdapter
/**
* Created by 小阿远 on 2017/10/17.
*/
public class ViewPagerAdapter extends FragmentPagerAdapter{
private static final int HOME_FRAGMENT = 0;
private static final int APP_FRAGMENT = 1;
private static final int GAME_FRAGMENT = 2;
private static final int SPECIAL_FRAGMENT = 3;
private static final int RECOMMEND_FRAGMENT = 4;
private static final int CLASSIFY_FRAGMENT = 5;
private static final int HOT_FRAGMENT = 6;
private final String[] mtitles;
public ViewPagerAdapter(FragmentManager fm,String[] titles) {
super(fm);
mtitles = titles;
}
@Override
public Fragment getItem(int position) {
switch (position){
case HOME_FRAGMENT:return new HomeFragment();
case APP_FRAGMENT:return new APPFragment();
case GAME_FRAGMENT:return new GameFragment();
case SPECIAL_FRAGMENT:return new SubjectFragment();
case RECOMMEND_FRAGMENT:return new RecommendFragment();
case CLASSIFY_FRAGMENT:return new ClassifyFragment();
case HOT_FRAGMENT:return new HotFragment();
}
return null;
}
@Override
public int getCount() {
return mtitles.length;
}
@Override
public CharSequence getPageTitle(int position) {
return mtitles[position];
}
}