1、我们创建一个activity,然后添加ViewPager2的布局
<?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" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <androidx.viewpager2.widget.ViewPager2 android:id="@+id/vp_main" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
将需要展示的界面都添加到CopyOnWriteArrayList中并创建对应的Adapter,如下:
public class PageAdapter extends FragmentStateAdapter { private CopyOnWriteArrayList<Fragment> fragments; public PageAdapter(@NonNull FragmentActivity fragmentActivity, CopyOnWriteArrayList<Fragment> fragments) { super(fragmentActivity); this.fragments = fragments; } public PageAdapter(@NonNull FragmentActivity fragmentActivity) { super(fragmentActivity); } @NonNull @Override public Fragment createFragment(int position) { return fragments.get(position); } @Override public int getItemCount() { return fragments.size(); } } CopyOnWriteArrayList fragments = new CopyOnWriteArrayList<>();
fragments.add(fragment界面1)
fragments.add(fragment界面2)
fragments.add(fragment界面3)...
ViewPager2.setAdapter(PageAdapter);
viewPager2.setOffscreenPageLimit(3);//表示三个界面之间来回切换都不会重新加载
viewPager2.setCurrentItem(0)//设置当前界面
2、引入第三方库
implementation 'com.r0adkll:slidableactivity:2.0.5'
在对应界面添加如下代码即可实现
SlidrConfig config = new SlidrConfig.Builder() .position(SlidrPosition.TOP) .scrimStartAlpha(1f) .scrimEndAlpha(1f) .edge(false) .build(); Slidr.attach(this, config);