你可以在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的結合使用。