public class MainActivity extends AppCompatActivity {
private String[] titles = new String[] { "首页", "Android", "iOS", "前端", "推荐",
"产品" };
private TabLayout mTabLayout;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
MyViewPagerAdapt myViewPagerAdapt = new MyViewPagerAdapt(getSupportFragmentManager());
mViewPager.setAdapter(myViewPagerAdapt);
mTabLayout.setupWithViewPager(mViewPager);
mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
}
class MyViewPagerAdapt extends FragmentPagerAdapter{
public MyViewPagerAdapt(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return new myFragment();
}
@Override
public int getCount() {
return titles.length;
}
/**
* 重写这个方法设置标题
* @param position
* @return
*/
@Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
}
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="@+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#f00"
app:tabSelectedTextColor="#0ff"
/>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="@android:color/white" />
</LinearLayout>