0

I have a ViewPagerAdapter that extends FragmentStateAdapter. The code below showcases said adapter.

public class ViewPagerAdapter extends FragmentStateAdapter {



    public ViewPagerAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle) {
        super(fragmentManager, lifecycle);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        switch (position) {
            case 0:
                return new HomeFragment();
            case 1:
                return new MapsFragment();
            case 2:
                return new BlankFragment();
            case 3:
                return new LeaderboardFragment();
            case 4:
                return new ProfileFragment();
            default:
                break;
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }

    @Override
    public int getItemCount() {
        return 5;
    }



}

In my main activity I initialize said adapter and a ViewPager2 inside onCreate as follows.

myViewPager2 = findViewById(R.id.pager);
        tabLayout = findViewById(R.id.mainTabs);

        myAdapter = new ViewPagerAdapter(getSupportFragmentManager(), getLifecycle());
        myViewPager2.setAdapter(myAdapter);
        myViewPager2.setUserInputEnabled(false);
        new TabLayoutMediator(tabLayout, myViewPager2,
                ((tab, position) -> tab.setText(tabsArray[position]))).attach();

        myViewPager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);

        // Set the icons for the tab layout
        tabLayout.getTabAt(0).setIcon(tabIcons[0]);
        tabLayout.getTabAt(1).setIcon(tabIcons[1]);
        tabLayout.getTabAt(2).setIcon(tabIcons[2]);
        tabLayout.getTabAt(3).setIcon(tabIcons[3]);
        tabLayout.getTabAt(4).setIcon(tabIcons[4]);

        tabLayout.getTabAt(2).view.setOnClickListener(view -> {
            Intent intent = new Intent(InsideActivity.this, CreatePostActivity.class);
            intent.putExtra("user_type",viewModel.getUserType());
            intent.putExtra("uid", viewModel.getCurrentUserId());
            InsideActivity.this.startActivity(intent);
        });

My issue is that the first time I click on the 4th page, the 5th is loaded instead. After that anytime I then click on the 4th it loads correctly. Also I have disabled horizontal scrolling. Any other page loads correctly. What am I doing wrong?

James Ele
  • 43
  • 6

0 Answers0