gradle中添加依赖
*compile'com.android.support:design:26+'
<android.support.design.widget.TabLayout android:layout_width="match_parent" android:layout_height="wrap_content" app:tabSelectedTextColor="@color/ble" app:tabTextColor="@color/colorAccent" app:tabTextAppearance="di" android:id="@+id/tab"></android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager android:layout_width="match_parent" android:layout_height="0px" android:layout_weight="1" android:id="@+id/vp"/>
public class MainActivity extends FragmentActivity { private TabLayout tb; List<Fragment> list=new ArrayList<>(); List<String> listtile=new ArrayList<>(); private ViewPager vp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); addfrag(); addlist(); tb = findViewById(R.id.tb); vp = findViewById(R.id.vp); vp.setAdapter(new Mypager(getSupportFragmentManager()));//设置TabLayout的模式tb.setTabMode(TabLayout.MODE_SCROLLABLE);//让tablayout和Viewpager关联;
tb.setupWithViewPager(vp); } private void addlist() { listtile.add("你猜"); listtile.add("不猜"); listtile.add("爱猜不猜"); } class Mypager extends FragmentPagerAdapter{ public Mypager(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { return list.get(position); } @Override public int getCount() { return list.size(); }//需要重写个返回标题的方法;
@Override public CharSequence getPageTitle(int position) { return listtile.get(position); } } private void addfrag() { for (int i=0;i<3;i++){ list.add(new F1()); } }}