第一步导入tablayout的依赖
在module里的build.gradle
compile ‘com.android.support:design:25.3.1’
如果和本项目的V7包冲突,只需要把版本号改成一致就可以了
写布局,注意Tablayout是support.design.widget下的
<android.support.design.widget.TabLayout
android:id="@+id/tablayout"
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
app:tabMode=“scrollable”
app:tabSelectedTextColor="#FC4E4E"
></android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"></android.support.v4.view.ViewPager>
创建fragment布局
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="fragment"
android:textSize="40sp" />
创建fragment public class MyFragment extends Fragment { public static final String ARG_PAGE = "ARG_PAGE"; private int mPage;
public static MyFragment newInstance(int Page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, Page);
MyFragment myFragment = new MyFragment();
myFragment.setArguments(args);
return myFragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_layout,container,false);
TextView tv = (TextView) view.findViewById(R.id.tv);
tv.setText("FragMent #" + mPage);
return view;
}
}
我们使用的是ViewPager结合Fragment,所以要配置适配器FragMentPagerAdapter
public class MyFragmentAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 9;
private String tabTitles[] = new String[]{“tab1”, “tab2”, “tab3”, “tab4”, “tab5”, “tab6”, “tab7”, “tab8”, “tab9”};
private Context context;
public MyFragmentAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
@Override
public Fragment getItem(int position) {
return MyFragment.newInstance(position + 1);
}
@Override
public int getCount() {
return PAGE_COUNT;
}
@Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
适配器与fragmen都写完了,接下来在Activity里面
public class TabActivity extends FragmentActivity {
private ViewPager vp;
private MyFragmentAdapter adapter;
private TabLayout tabLayout;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_layout);
vp = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.tablayout);
//配置适配器
adapter = new MyFragmentAdapter(getSupportFragmentManager(), TabActivity.this);
vp.setAdapter(adapter);
tabLayout.setupWithViewPager(vp);