1.添加依赖
com.android.support:design:25.3.1
2.XML布局文件
<android.support.design.widget.TabLayout
android:id="@+id/TabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
></android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/ViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/TabLayout"></android.support.v4.view.ViewPager>
3.代码实现
public class MainActivity extends AppCompatActivity {
private TabLayout mTabLayout;
private ArrayList<Fragment> mList = new ArrayList<>();
private AFragment aFragment;
private BFragment bFragment;
private CFragment cFragment;
private ViewPager mViewPager;
private MyAdapter myAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView(){
mTabLayout = (TabLayout) findViewById(R.id.TabLayout);
mViewPager = (ViewPager) findViewById(R.id.ViewPager);
aFragment = new AFragment();
bFragment = new BFragment();
cFragment = new CFragment();
mList.add(aFragment);
mList.add(bFragment);
mList.add(cFragment);
myAdapter = new MyAdapter(getSupportFragmentManager(),mList);
mViewPager.setAdapter(myAdapter);
mTabLayout.setupWithViewPager(mViewPager);
mTabLayout.getTabAt(0).setText("电影");
mTabLayout.getTabAt(1).setText("音乐");
mTabLayout.getTabAt(2).setText("阅读");
}
}
来源:oschina
链接:https://my.oschina.net/u/3713591/blog/1555063