在Android中,ViewPager是一個可以左右滑動的容器,可以用來顯示多個頁面,并且可以通過滑動或者點擊指示器來切換頁面。以下是使用ViewPager的步驟:
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
public class MyAdapter extends PagerAdapter {
private List<View> mViewList;
public MyAdapter(List<View> viewList) {
mViewList = viewList;
}
@Override
public int getCount() {
return mViewList.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView(mViewList.get(position));
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
View view = mViewList.get(position);
container.addView(view);
return view;
}
}
ViewPager viewPager = findViewById(R.id.viewPager);
List<View> viewList = new ArrayList<>();
// 添加要顯示的頁面到viewList
MyAdapter adapter = new MyAdapter(viewList);
viewPager.setAdapter(adapter);
TabLayout tabLayout = findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
通過以上步驟,就可以在Android中使用ViewPager來實現頁面的左右滑動切換了。