1.在gradle引入design库
compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.android.support:design:23.4.0'
2.主页面布局
<?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: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" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" /> <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>
3.adapter布局
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" />
4.adapter代码
public class SimpleFragmentAdapter extends FragmentPagerAdapter { final int PAGE_COUNT = 3; private String tabTitles[] = new String[]{"tabl","tab2","tab2"}; private Context context; public SimpleFragmentAdapter(FragmentManager fm,Context context) { super(fm); this.context = context; } @Override public Fragment getItem(int position) { return fragment.getInstance(position); } @Override public int getCount() { return PAGE_COUNT; } @Override public CharSequence getPageTitle(int position) { return tabTitles[position]; } }
5.framgent代码
public class fragment extends Fragment { public static String tag = "fragment"; private int num; public static fragment getInstance(int num){ Bundle bundle = new Bundle(); bundle.putInt(tag,num); fragment fg = new fragment(); fg.setArguments(bundle); return fg; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); num = getArguments().getInt(tag); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_content, container, false); TextView tv = (TextView)view; tv.setText("Fragment++"+num); return view; }
6.MainActivity代码
public class MainActivity extends AppCompatActivity { private SimpleFragmentAdapter fragmentAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fragmentAdapter = new SimpleFragmentAdapter(getSupportFragmentManager(), this); ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); viewPager.setAdapter(fragmentAdapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs); tabLayout.setupWithViewPager(viewPager); tabLayout.setTabMode(TabLayout.MODE_FIXED); } }7,综上所述就实现了TabLayout最简单的用法了。