Android studio中java用viewpager2写引导页,并且每页都是一个fragment
时间: 2024-05-12 18:20:37 浏览: 173
Android Studio版本的ViewPager+Fragment
1.在build.gradle文件中添加以下依赖项:
```
implementation 'androidx.viewpager2:viewpager2:1.0.0'
```
2.在XML布局文件中添加ViewPager2:
```
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewPager2"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
3.创建一个Fragment类来表示每一页的内容:
```
public class PageFragment extends Fragment {
private int pageNumber;
public PageFragment(int pageNumber) {
this.pageNumber = pageNumber;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_page, container, false);
TextView textView = view.findViewById(R.id.textView);
textView.setText("Page " + pageNumber);
return view;
}
}
```
4.创建一个FragmentStateAdapter类来管理ViewPager2中的Fragment:
```
public class PagerAdapter extends FragmentStateAdapter {
private int numPages;
public PagerAdapter(FragmentActivity fa, int numPages) {
super(fa);
this.numPages = numPages;
}
@Override
public Fragment createFragment(int position) {
return new PageFragment(position);
}
@Override
public int getItemCount() {
return numPages;
}
}
```
5.在MainActivity中设置ViewPager2和PagerAdapter:
```
ViewPager2 viewPager2 = findViewById(R.id.viewPager2);
PagerAdapter pagerAdapter = new PagerAdapter(this, 3); // 3表示总页数
viewPager2.setAdapter(pagerAdapter);
```
这样,每一页都会显示一个PageFragment,可以在PageFragment中添加自己的布局和逻辑。
阅读全文