<android.support.design.widget.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content"></android.support.design.widget.TabLayout> <android.support.v4.view.ViewPager android:id="@+id/vp" android:layout_width="match_parent" android:layout_height="wrap_content"/>
public class MainActivity extends AppCompatActivity { private ViewPager vp; private TabLayout tab_layout; private List<String> titleList; private List<Fragment> fragList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tab_layout = findViewById(R.id.tab_layout); vp = findViewById(R.id.vp); titleList = new ArrayList<String>(); fragList = new ArrayList<>(); titleList.add("花边"); titleList.add("推荐"); titleList.add("热点"); titleList.add("广告"); titleList.add("其他"); for (String title :titleList){ tab_layout.addTab(tab_layout.newTab().setText(title)); fragList.add(new NewsFragment()); } //设置默认模式 tab_layout.setTabMode(TabLayout.MODE_FIXED); //设置导航文本颜色 tab_layout.setTabTextColors(ColorStateList.valueOf(Color.BLACK)); //创建适配器 vp.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public Fragment getItem(int position) { return fragList.get(position); } @Override public int getCount() { return fragList.size(); } @Nullable @Override public CharSequence getPageTitle(int position) { return titleList.get(position); } }); tab_layout.setupWithViewPager(vp); } }