你可以在ViewPager中放置一个包含多个RecyclerView的Fragment,这样就可以在ViewPager的每个页面中显示不同的RecyclerView。以下是一个简单的示例代码:
public class MyRecyclerViewFragment extends Fragment {
private RecyclerView recyclerView;
private RecyclerViewAdapter adapter;
public MyRecyclerViewFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recycler_view, container, false);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
adapter = new RecyclerViewAdapter();
recyclerView.setAdapter(adapter);
return view;
}
}
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private PagerAdapter pagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.viewPager);
pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return new MyRecyclerViewFragment();
}
@Override
public int getCount() {
return 3; // 3个页面
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<?xml version="1.0" encoding="utf-8"?>
<androidx.viewpager.widget.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
通过以上代码,你可以在ViewPager的每个页面中显示不同的RecyclerView,从而实现RecyclerView和ViewPager的结合使用。