使用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的基本使用方法,你可以根據自己的需求進行擴展和定制。