1. Are you ready for the Galaxy S20? Here is everything we know so far!

Adapter and ViewPage2 error: incompatible types: ViewPager2 cannot be converted to ViewPager

Discussion in 'Android Development' started by CristiAlex92, Oct 3, 2019.

  1. CristiAlex92

    CristiAlex92 Lurker
    Thread Starter


    I'm trying to build a hello world app with tabs.
    The problem I'm encountering now is that I get some errors, using adapter on ViewPager2.
    I updated from ViewPager to ViewPager2.

    Here's the code:

    app > java > MainActivity.java

    Code (Java):
    1. public class MainActivity extends AppCompatActivity {
    2.     private Toolbar toolbar;
    3.     private ViewPagerAdapter adapter;
    4.     private TabLayout tabLayout;
    5.     private Spinner spinner2;
    7.     @Override
    8.     protected void onCreate(Bundle savedInstanceState) {
    9.         super.onCreate(savedInstanceState);
    10.         setContentView(R.layout.activity_main);
    12.         //this creates the three-dot button in the right on the toolbar
    13.         Toolbar toolbar = findViewById(R.id.toolbar);
    14.         //uses toolbar as action bar
    15.         setSupportActionBar(toolbar);
    17.         ViewPager2 viewPager2 = findViewById(R.id.pager);
    18.         adapter = new ViewPagerAdapter(getSupportFragmentManager());
    19.         viewPager2.setAdapter(adapter); // <- adapter in this line is the problem (error: incompatible types: ViewPagerAdapter cannot be converted to Adapter)
    21.         tabLayout = findViewById(R.id.tabs);
    22.         tabLayout.setupWithViewPager(viewPager2); // <- and this variable: viewPager2 (error: incompatible types: ViewPager2 cannot be converted to ViewPager)
    23.     }
    app > res > layout > activity_main.xml

    Code (Text):
    1. <androidx.viewpager2.widget.ViewPager2
    2.     android:id="@+id/pager"
    3.     android:layout_width="match_parent"
    4.     android:layout_height="match_parent" />
    Dependencies I have:


    What's wrong?

    1. Download the Forums for Android™ app!


  2. Hi, can you add the adapter code?
  3. CristiAlex92

    CristiAlex92 Lurker
    Thread Starter

    What adapter?
  4. Something similar happened to me, it was caused because I was importing androidx.fragment.app.FragmentStatePagerAdapter instead of androidx.viewpager2.adapter.FragmentStateAdapter

Share This Page