viewPager和tabLayout使用示范代码
时间: 2023-04-09 21:01:31 浏览: 118
ViewPager示例代码
以下是一个简单的ViewPager和TabLayout的使用示范代码:
1. 在布局文件中添加ViewPager和TabLayout:
```
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
app:tabTextColor="@android:color/white"
app:tabSelectedTextColor="@android:color/white"
app:tabIndicatorColor="@android:color/white"/>
```
2. 在Activity或Fragment中设置ViewPager和TabLayout:
```
// 获取ViewPager和TabLayout
ViewPager viewPager = findViewById(R.id.viewPager);
TabLayout tabLayout = findViewById(R.id.tabLayout);
// 创建Fragment列表和标题列表
List<Fragment> fragmentList = new ArrayList<>();
List<String> titleList = new ArrayList<>();
fragmentList.add(new Fragment1());
fragmentList.add(new Fragment2());
titleList.add("Tab1");
titleList.add("Tab2");
// 创建PagerAdapter并设置给ViewPager
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), fragmentList, titleList);
viewPager.setAdapter(pagerAdapter);
// 将TabLayout与ViewPager关联
tabLayout.setupWithViewPager(viewPager);
```
3. 创建PagerAdapter类:
```
public class PagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragmentList;
private List<String> titleList;
public PagerAdapter(FragmentManager fm, List<Fragment> fragmentList, List<String> titleList) {
super(fm);
this.fragmentList = fragmentList;
this.titleList = titleList;
}
@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);
}
}
```
这样就可以实现一个简单的ViewPager和TabLayout的效果了。
阅读全文