TabLayout实现左右滑动效果
时间: 2024-06-11 17:09:16 浏览: 102
TabLayout本身并不支持左右滑动效果,但可以结合ViewPager实现。具体实现步骤如下:
1.在布局文件中添加TabLayout和ViewPager:
```
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabGravity="fill"/>
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
```
其中,tabMode设置为scrollable,表示TabLayout可以左右滑动;tabGravity设置为fill,表示TabLayout中的Tab均分宽度。
2.创建FragmentPagerAdapter,并设置给ViewPager:
```
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragments;
private List<String> mTitles;
public MyPagerAdapter(FragmentManager fm, List<Fragment> fragments, List<String> titles) {
super(fm);
mFragments = fragments;
mTitles = titles;
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public CharSequence getPageTitle(int position) {
return mTitles.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
}
// 在Activity中设置PagerAdapter
List<Fragment> fragments = new ArrayList<>();
fragments.add(new Fragment1());
fragments.add(new Fragment2());
fragments.add(new Fragment3());
List<String> titles = new ArrayList<>();
titles.add("Tab1");
titles.add("Tab2");
titles.add("Tab3");
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager(), fragments, titles);
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(adapter);
```
3.将ViewPager设置给TabLayout:
```
TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
```
至此,TabLayout就能够实现左右滑动效果了。
阅读全文