在ViewPager2中使用Fragment来代替直接使用View作为页面。这样可以避免ViewPager2重置Activity的视图。
示例代码:
public class MyFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //创建需要的页面UI View rootView = inflater.inflate(R.layout.my_fragment_layout, container, false); return rootView; } }
public class MainActivity extends AppCompatActivity {
...
private List
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.view_pager);
fragmentList.add(new MyFragment());
fragmentList.add(new MyFragment());
fragmentList.add(new MyFragment());
viewPager.setAdapter(new MyFragmentAdapter(this, fragmentList));
}
}
public class MyFragmentAdapter extends FragmentStateAdapter {
private List
public MyFragmentAdapter(@NonNull FragmentActivity fragmentActivity, List fragmentList) {
super(fragmentActivity);
this.fragmentList = fragmentList;
}
@NonNull
@Override
public Fragment createFragment(int position) {
return fragmentList.get(position);
}
@Override
public int getItemCount() {
return fragmentList.size();
}
}