你可以在ViewPager中放置一个包含多个RecyclerView的Fragment,这样就可以在ViewPager的每个页面中显示不同的RecyclerView。以下是一个简单的示例代码:
- 创建一个包含RecyclerView的Fragment:
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; } }
- 创建一个包含ViewPager和多个MyRecyclerViewFragment的Activity:
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个页面 } } }
- 创建RecyclerView的布局文件 fragment_recycler_view.xml:
- 创建ViewPager的布局文件 activity_main.xml:
通过以上代码,你可以在ViewPager的每个页面中显示不同的RecyclerView,从而实现RecyclerView和ViewPager的结合使用。