The AV
The AV

Reputation: 129

Switching Fragments in a viewpager on clicking items in Navigation Drawer

Even after seeing number of questions on Stack Overflow, I did not get a proper answer and thus writing this. I have created a Tab Layout in a View Pager.

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:layout_scrollFlags="scroll|enterAlways"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

            <android.support.design.widget.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabGravity="fill"
                app:tabMode="scrollable"
                app:tabTextAppearance="@style/TabTextAppearance"/>
        </android.support.design.widget.AppBarLayout>
        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    </android.support.design.widget.CoordinatorLayout>
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/navheader"
        app:menu="@menu/menu_navigation" />
</android.support.v4.widget.DrawerLayout>

I have coded this from Google Code Lab Material Design. My Basic Requirement:

There are six tabs or fragments in the view pager. The corresponding six options also appear on pulling the Navigation Drawer. When I click an item in my Drawer say item number 4, there must be a swamp from the current tab or fragment to the respective 4th tab or fragment.

Code in my Main Activity:

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Adding Toolbar to Main screen
        mHandler = new Handler();
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Setting ViewPager for each Tabs
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);
        // Set Tabs inside Toolbar
        TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
        tabs.setupWithViewPager(viewPager);
        // Create Navigation drawer and inlfate layout
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        // Adding menu icon to Toolbar
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            VectorDrawableCompat indicator =
                    VectorDrawableCompat.create(getResources(), R.drawable.ic_menu, getTheme());
            indicator.setTint(ResourcesCompat.getColor(getResources(), R.color.white, getTheme()));
            supportActionBar.setHomeAsUpIndicator(indicator);
            supportActionBar.setDisplayHomeAsUpEnabled(true);
        }
        // Set behavior of Navigation drawer
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    // This method will trigger on item Click of navigation menu

//                    public boolean onNavigationItemSelected(MenuItem menuItem) {
//                        // Set item in checked state
//                        menuItem.setChecked(true);
//
//                        // TODO: handle navigation
//
//                        // Closing drawer on item click
//                        mDrawerLayout.closeDrawers();
//                        return true;
//                    }


                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {

                        //Check to see which item was being clicked and perform appropriate action
                        switch (menuItem.getItemId()) {
                            //Replacing the main content with ContentFragment Which is our Inbox View;
                            case R.id.nav_home:
                                navItemIndex = 0;
                                CURRENT_TAG = TAG_HOME;
                                break;
                            case R.id.nav_history:
                                navItemIndex = 1;
                                CURRENT_TAG = TAG_HISTORY;
                                break;
                            case R.id.nav_location:
                                navItemIndex = 2;
                                CURRENT_TAG = TAG_LOCATION;
                                break;
                            case R.id.nav_developments:
                                navItemIndex = 3;
                                CURRENT_TAG = TAG_DEVELOPMENTS;
                                break;
                            case R.id.nav_donations:
                                navItemIndex = 4;
                                CURRENT_TAG = TAG_DONATIONS;
                                break;
                            case R.id.nav_resources:
                                navItemIndex = 5;
                                CURRENT_TAG = TAG_RESOURCES;
                                break;
                            case R.id.nav_feedback:
                                navItemIndex = 6;
                                CURRENT_TAG = TAG_FEEDBACK;
                                break;
                            case R.id.nav_contactus:
                                navItemIndex = 7;
                                CURRENT_TAG = TAG_CONTACTUS;
                                break;

                            default:
                                navItemIndex = 0;
                        }

                        //Checking if the item is in checked state or not, if not make it in checked state
                        if (menuItem.isChecked()) {
                            menuItem.setChecked(false);
                        } else {
                            menuItem.setChecked(true);
                        }
                        menuItem.setChecked(true);

                        loadHomeFragment();

                        return true;
                    }
                });
        // Adding Floating Action Button to bottom right of main view

    }

    private void loadHomeFragment() {

        // if user select the current navigation menu again, don't do anything
        // just close the navigation drawer
        if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
            mDrawerLayout.closeDrawers();

            // show or hide the fab button

            return;
        }

        // Sometimes, when fragment has huge data, screen seems hanging
        // when switching between navigation menus
        // So using runnable, the fragment is loaded with cross fade effect
        // This effect can be seen in GMail app
        Runnable mPendingRunnable = new Runnable() {
            @Override
            public void run() {
                // update the main content by replacing fragments



                Fragment fragment = getHomeFragment();
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

                fragmentTransaction.replace(R.id.viewpager, fragment, CURRENT_TAG);
                fragmentTransaction.commitAllowingStateLoss();
            }
        };

        // If mPendingRunnable is not null, then add to the message queue
        if (mPendingRunnable != null) {
            mHandler.post(mPendingRunnable);
        }

        // show or hide the fab button


        //Closing drawer on item click
        mDrawerLayout.closeDrawers();


    }



    private Fragment getHomeFragment() {
        switch (navItemIndex) {
            case 0:
                // home
                one_main oneMain = new one_main();
                return oneMain;
            case 1:
                // photos
                one_fragment oneFragment = new one_fragment();
                return oneFragment;
            case 2:
                // movies fragment
                two_location twoLocation = new two_location();
                return twoLocation;
            case 3:
                // notifications fragment
                four_future fourFuture = new four_future();
                return fourFuture;

            case 4:
                // settings fragment
                three_donation threeDonation = new three_donation();
                return threeDonation;

            case 5:
                // movies fragment
                six_download sixDownload = new six_download();
                return sixDownload;
            case 6:
                // notifications fragment
                five_feedback fiveFeedback = new five_feedback();
                return fiveFeedback;

            case 7:
                // settings fragment
                seven_contact sevenContact = new seven_contact();
                return sevenContact;
            default:
                return new one_main();
        }
    }

I am able to open my app. I am able to navigate between Tabs. I am able to pull out the Drawer Layout. However when I click on any item in the Drawer, there is swap to the respective tab. But everything in the tab becomes empty. How to solve this?

Or is there any better solution for fragment switching on items clicked in Drawer Layout? If yes, kindly point to a detailed tutorial.

Upvotes: 1

Views: 1714

Answers (3)

Saad Mansoor
Saad Mansoor

Reputation: 365

InshaAllah this will solve your issue. (you can jump to step3 directly)

Step1: make a simple tabLayout that attaches to the viewPager and on swapping on the viewPager, fragments are changed. (see youtube tutorial: https://www.youtube.com/watch?v=ZnhSbXuJaqQ ).

Step2: make a navigation drawer. add onclick on its items. (youtube tutorial: https://www.youtube.com/watch?v=HEDHabooHO0 )

Step3: write viewPager.setCurrentItem(0); on your first navigation item viewPager.setCurrentItem(01); on your 2nd navigation item viewPager.setCurrentItem(02); on your 3rd navigation item . . . till n-1 number of times. n means the amount of fragments you have.

Reason: you remember in step1, that the code responsible for switching of fragments in the viewPager was : viewPager.setCurrentItem(tab.getPosition()); . And

tab.getPosition() was responsible for determining the number of the fragment where you want to move to. So, I wrote 0, 01, 02 in those small brackets instead of .

Upvotes: 0

Le Thanh Tan
Le Thanh Tan

Reputation: 11

I hope, It can help you

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    int id = item.getItemId();
    displayView(id);
    return true;
}

public void displayView(int viewId) {

    Fragment fragment = null;

    switch (viewId) {
        case R.id.nav_home:
            fragment = new HomeFragment();
            txtToolbarTitle.setText(getResources().getString(R.string.ac_home));
            break;
        case R.id.nav_budget:
            fragment = new BudgetFragment();
            txtToolbarTitle.setText(getResources().getString(R.string.ac_budget));
            break;
        case R.id.nav_asset:
            fragment = new AssetFragment();
            txtToolbarTitle.setText(getResources().getString(R.string.ac_asset));
            fab.hide();
            break;
        case R.id.nav_note:
            fragment = new NotesFragment();
            txtToolbarTitle.setText(getResources().getString(R.string.ac_note));
            //toolbar.setG
            break;
        case R.id.nav_repeat:
            fragment = new RepeatFragment();
            txtToolbarTitle.setText(getResources().getString(R.string.ac_repeat));
            break;
        case R.id.nav_payment:
            fragment = new PaymentPlanFragment();
            txtToolbarTitle.setText(getResources().getString(R.string.ac_payment));
            break;
        case R.id.nav_setting:
            fragment = new SettingFragment();
            txtToolbarTitle.setText(getResources().getString(R.string.ac_setting));
            break;
    }

    if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.containerView, fragment);
        ft.commit();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
}

Upvotes: 1

The AV
The AV

Reputation: 129

I was able to solve the problem by using the below piece of code:

viewPager.setCurrentItem(navItemIndex)

in navigationView.setNavigationItemSelectedListener

Upvotes: 1

Related Questions