首先要导个依赖包这个包属于TabLayout :
compile 'com.android.support:design:26+'
下面代码是在,XML里的:
<?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" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="zhaochuang.bawei.com.day_rikao.MainActivity"> <android.support.design.widget.TabLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/tab" ></android.support.design.widget.TabLayout> <android.support.v4.view.ViewPager android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:id="@+id/vp" ></android.support.v4.view.ViewPager> </LinearLayout> 下面代码是一个Fragment的普通方法 public class BlankFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { TextView textView = new TextView(getActivity()); double random = Math.random(); textView.setText("xxxxxxxxxxx"+random); return textView; } 然后在MianActivity调用了上面这些个方法,如一下代码 package com.bwie.tablayoutdemo2; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import java.util.ArrayList; /** * 1--tablayout * 2--- viewPager * 3--viewPagerAdapter * 4-- 让TabLayout和Viewpager关联; */ public class MainActivity extends AppCompatActivity { private TabLayout tabLayout; private ViewPager viewPager; ArrayList<Fragment> fragmentList = new ArrayList<Fragment>(); ArrayList<String> titleList = new ArrayList<String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabLayout = (TabLayout) findViewById(R.id.tabLayout); viewPager = (ViewPager) findViewById(R.id.viewPager); initData(); //ctrl+p 提示参数的快捷键 MPagerAdapter mPagerAdapter = new MPagerAdapter(getSupportFragmentManager()); viewPager.setAdapter(mPagerAdapter); //设置TabLayout的模式 tabLayout.setTabMode(TabLayout.MODE_FIXED); //让tablayout和Viewpager关联; tabLayout.setupWithViewPager(viewPager); } private void initData() { for (int i = 0; i <4 ; i++) { fragmentList.add(new BlankFragment()); titleList.add("爱因斯坦" +i); } } class MPagerAdapter extends FragmentPagerAdapter{ public MPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { return fragmentList.get(position); } @Override public int getCount() { return fragmentList.size(); } //需要重写个返回标题的方法; @Override public CharSequence getPageTitle(int position) { return titleList.get(position); } } }