使用ViewPager需要以下步骤:
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
public class MyPagerAdapter extends PagerAdapter {
private List<View> views;
public MyPagerAdapter(List<View> views) {
this.views = views;
}
@Override
public int getCount() {
return views.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
View view = views.get(position);
container.addView(view);
return view;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView(views.get(position));
}
}
ViewPager viewPager = findViewById(R.id.viewPager);
// 创建View集合
List<View> views = new ArrayList<>();
views.add(view1);
views.add(view2);
views.add(view3);
// 创建适配器
MyPagerAdapter adapter = new MyPagerAdapter(views);
// 设置适配器
viewPager.setAdapter(adapter);
以上是ViewPager的基本使用方法,你可以根据自己的需求进行扩展和定制。