帮我写一份Android Viewpagger2+fragment实现分页滑动效果
时间: 2023-12-27 13:05:21 浏览: 101
Android Viewpagger2+Fragment实现UI切换效果 demo
好的,下面是实现步骤:
1. 在 build.gradle 文件中添加以下依赖:
```
dependencies {
implementation 'androidx.viewpager2:viewpager2:1.0.0'
}
```
2. 在布局文件中添加 ViewPager2:
```xml
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewPager2"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
3. 创建 Fragment:
```java
public class MyFragment extends Fragment {
private int mPage;
public static MyFragment newInstance(int page) {
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("page", page);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt("page");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my, container, false);
TextView textView = view.findViewById(R.id.textView);
textView.setText("Page " + mPage);
return view;
}
}
```
4. 创建 FragmentAdapter:
```java
public class MyFragmentAdapter extends FragmentStateAdapter {
private int mItemCount;
public MyFragmentAdapter(FragmentActivity fragmentActivity, int itemCount) {
super(fragmentActivity);
mItemCount = itemCount;
}
@Override
public Fragment createFragment(int position) {
return MyFragment.newInstance(position);
}
@Override
public int getItemCount() {
return mItemCount;
}
}
```
5. 在 Activity 中设置 ViewPager2:
```java
ViewPager2 viewPager2 = findViewById(R.id.viewPager2);
MyFragmentAdapter adapter = new MyFragmentAdapter(this, 5); // 设置 Fragment 数量
viewPager2.setAdapter(adapter);
```
这样就完成了 ViewPager2 + Fragment 实现分页滑动效果的实现。
阅读全文