安卓里面Fragmen和ViewParger2结合使用代码
时间: 2023-03-22 21:01:38 浏览: 100
在Android中,可以使用Fragment和ViewPager2组合来创建可滑动的页面,以下是一个示例代码:
1. 创建两个Fragment:
FragmentOne.java
```java
public class FragmentOne extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
TextView textView = view.findViewById(R.id.text_view);
textView.setText("Fragment One");
return view;
}
}
```
FragmentTwo.java
```java
public class FragmentTwo extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
TextView textView = view.findViewById(R.id.text_view);
textView.setText("Fragment Two");
return view;
}
}
```
2. 在布局文件中添加ViewPager2:
activity_main.xml
```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/constraint_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
```
3. 在MainActivity中设置ViewPager2:
MainActivity.java
```java
public class MainActivity extends AppCompatActivity {
private ViewPager2 viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.view_pager);
List<Fragment> fragmentList = new ArrayList<>();
fragmentList.add(new FragmentOne());
fragmentList.add(new FragmentTwo());
FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager(), getLifecycle(), fragmentList);
viewPager.setAdapter(adapter);
}
}
```
4. 创建FragmentAdapter:
```java
public class FragmentAdapter extends FragmentStateAdapter {
private List<Fragment> fragmentList;
public FragmentAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle, List<Fragment> fragmentList) {
super(fragmentManager, lifecycle);
this.fragmentList = fragmentList;
}
@NonNull
@Override
public Fragment createFragment(int position) {
return fragmentList.get(position);
}
@Override
public int getItemCount() {
return fragmentList.size();
}
}
```
这样就可以在ViewPager2中使用两个Fragment了。
阅读全文