Search code examples
javaandroidandroid-recyclerviewandroid-viewpager2

Why RecyclerView adapter for ViewPager2?


Why do we use RecyclerView adapter for the ViewPager2? Why doesn't it use its own class for the adapter? I see ViewPager2's class and it does not extend or do anything with reycler view. Then why RecyclerView's adapter?


Solution

  • Because ViewPager2 is just a specialised container of a RecycyerView.

    It's a bit hidden

    But from the code

         private class RecyclerViewImpl extends RecyclerView {
            RecyclerViewImpl(@NonNull Context context) {
                super(context);
            }
    

    and then in the initialize method of viewpager2

    private void initialize(Context context, AttributeSet attrs) {
            mAccessibilityProvider = sFeatureEnhancedA11yEnabled
                    ? new PageAwareAccessibilityProvider()
                    : new BasicAccessibilityProvider();
            mRecyclerView = new RecyclerViewImpl(context);