user2519193
user2519193

Reputation: 211

How do I go to a specific fragment by clicking on something?

For example, I have a Navigation Drawer, and I want to be able to navigate straight to a drawer by clicking on items inside it. Here is my code.

    mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            //What do I put here??

        }


    });

What should I put, such that when the user clicks on something in the Navigation Drawer, the app will jump straight to the selected fragment?

Thanks!

EDIT: I think I managed to solve this, but since my application uses ViewPager to navigate through the fragments, I just use

    mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub

            viewPager.setCurrentItem(arg2);
                // Close drawer

        }


    });

And that works!

Upvotes: 0

Views: 1445

Answers (1)

linus
linus

Reputation: 481

Try this code inside OnItemClick:

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    // Locate Position
    switch (arg2) {
    case 0:
        ft.replace(R.id.content_frame, yourFragment1);
        break;
    case 1:
        ft.replace(R.id.content_frame, yourFragment2);
        break;
    case 2:
        ft.replace(R.id.content_frame, yourFragment3);
        break;
           // etc add more code if you want//
    }
    /* Commit fragment */
    ft.commit();
    mDrawerList.setItemChecked(position, true);
    // Close drawer
    mDrawerLayout.closeDrawer(mDrawerList);

Upvotes: 1

Related Questions