Search code examples
androidandroid-viewpagerswipeandroid-pageradapter

Android swiping through fragments not working


I have tried following the developer guide from developer.android.com

It's really confusing as not everything is up to date and most guides are outdated on the site and lots of methods are deprecated. So I'm left with all these new things like AppCompatActivity and FragmentStatePagerAdapter.

Anyways I tried my best but I still can't swipe between my fragments and I don't see why. Important thing to note here, I try not to use tabs.

Also I hate posting big blocks of code, but for future reference this might be important, so feel free to check the entire code out from my github project

MainActivity

public class MainActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private Drawer drawer;

    private ViewPager viewPager;
    private PagerAdapter pagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //initTabLayout(); --> needed?
        toolbar =(Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        initViewPager();
        initMaterialDrawer();
    }

    private void initViewPager() {
        viewPager = (ViewPager) findViewById(R.id.pager);
        pagerAdapter = new CustomPagerAdapter(getSupportFragmentManager(),CustomPagerAdapter.mNumOfTabs);
        viewPager.setAdapter(pagerAdapter);
    }

    @Override
    public void onBackPressed() {
        if(drawer != null && drawer.isDrawerOpen())
            drawer.closeDrawer();
        else
            super.onBackPressed();
    }
    private void initMaterialDrawer() {
        PrimaryDrawerItem item1 = new PrimaryDrawerItem().withName("Profile");
        PrimaryDrawerItem item2 = new PrimaryDrawerItem().withName("Organisations");
        PrimaryDrawerItem item3 = new PrimaryDrawerItem().withName("Extra Option");
        PrimaryDrawerItem item4 = new PrimaryDrawerItem().withName("Extra Option");

        AccountHeader headerResult = new AccountHeaderBuilder()
                .withActivity(this)
                .withHeaderBackground(R.drawable.drawer_background1)
                .withAlternativeProfileHeaderSwitching(false)
                .addProfiles(
                        new ProfileDrawerItem()
                                .withIsExpanded(false)
                                .withName("name here")
                                .withEmail("emailhere.com")
                                .withEnabled(false)
                                .withIcon(new IconDrawable(this, FontAwesomeIcons.fa_reddit))
                )
                .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {

                    @Override
                    public boolean onProfileChanged(View view, IProfile profile, boolean current) {
                        return false;
                    }
                })
                .build();

        //create the drawer and remember the `Drawer` result object
        drawer = new DrawerBuilder()
                .withActivity(this)
                .withToolbar(toolbar)
                .withAccountHeader(headerResult)
                .withTranslucentStatusBar(true)
                .addDrawerItems(
                        new PrimaryDrawerItem().withName("111111111").withIcon(new IconDrawable(this, FontAwesomeIcons.fa_sign_out)),
                        new PrimaryDrawerItem().withName("111111111").withIcon(new IconDrawable(this, FontAwesomeIcons.fa_sign_out)),
                        new PrimaryDrawerItem().withName("111111111").withIcon(new IconDrawable(this, FontAwesomeIcons.fa_sign_out)),
                        new SectionDrawerItem().withName("SECTION"),
                        new SecondaryDrawerItem().withName("22222").withIcon(new IconDrawable(this, FontAwesomeIcons.fa_sign_out)),
                        new SecondaryDrawerItem().withName("22222").withIcon(new IconDrawable(this, FontAwesomeIcons.fa_sign_out)),
                        new SecondaryDrawerItem().withName("22222").withIcon(new IconDrawable(this, FontAwesomeIcons.fa_sign_out)),
                        new SecondaryDrawerItem().withName("22222").withIcon(new IconDrawable(this, FontAwesomeIcons.fa_sign_out))
                )
                .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                    @Override
                    public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
                        if (drawerItem instanceof Nameable) {
                            Toast.makeText(MainActivity.this, ((Nameable) drawerItem).getName().getText(MainActivity.this), Toast.LENGTH_SHORT).show();
                        }
                        //true: do nothing
                        //false: close drawer
                        return true;
                    }
                }).build();

        drawer.addStickyFooterItem(new PrimaryDrawerItem()
                        .withName("Log out")
                        .withIcon(new IconDrawable(this, FontAwesomeIcons.fa_sign_out).alpha(100)));

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        drawer.getActionBarDrawerToggle().setDrawerIndicatorEnabled(true);
    }
}

main layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="be.kdg.kandoe.kandoe.activity.MainActivity">
    <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar">
    </include>
    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="fill_parent" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MAINACTIVITY"
        android:id="@+id/main_title"
        android:layout_below="@+id/toolbar"
        android:layout_alignParentStart="true" />

</RelativeLayout>

PagerAdapter

public class CustomPagerAdapter extends FragmentStatePagerAdapter {
    public static int mNumOfTabs;

    public CustomPagerAdapter(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new ChatFragment();
            case 1:
                return new GameFragment();
            case 2:
                return new CardFragment();
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return mNumOfTabs;
    }
}

Solution

  •  pagerAdapter = new CustomPagerAdapter(getSupportFragmentManager(),CustomPagerAdapter.mNumOfTabs);
    

    mNumOfTabs is not initialized in CustomPagerAdapter

    you need to be doing this..

     pagerAdapter = new CustomPagerAdapter(getSupportFragmentManager(),3);
    

    or

    public class CustomPagerAdapter extends FragmentStatePagerAdapter {
    
        public CustomPagerAdapter(FragmentManager fm) {
            super(fm);
        }
    
        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return new ChatFragment();
                case 1:
                    return new GameFragment();
                case 2:
                    return new CardFragment();
                default:
                    return null;
            }
        }
    
        @Override
        public int getCount() {
            return 3;
        }
    }
    

    And the adapter is set this way

    pagerAdapter = new CustomPagerAdapter(getSupportFragmentManager());
    

    And your main layout needs to have LinearLayout with orientation vertical to have a perfect look. Just see the difference by working with existing code before changing it to