How to select the first item in a navigation drawer and open a fragment on application start
Asked Answered
H

9

16

I have created MainActivity with NavigationView. When Activity is opened I want to automatically select the first item in the navigation drawer and open Fragment under that item. I've searched a lot but didn't find any proper solutions.

What is the proper way to do this ?

Main Activity:

public class MainActivity extends AppCompatActivity implements Config {

private NavigationView navigationView;
private DrawerLayout drawerLayout;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    toolbar.setTitleTextColor(getResources().getColor(R.color.colorIcons));

    if (null != getSupportActionBar())
        getSupportActionBar().setLogo(R.drawable.ic_blogger_white);

    //Start PostListFragmentWebView
    /*PostListFragmentWebView postListFragmentWebView = new PostListFragmentWebView();
    getSupportFragmentManager().beginTransaction()
            .replace(R.id.frame, postListFragmentWebView)
            .commit();*/

    //Initializing NavigationView
    navigationView = (NavigationView) findViewById(R.id.navigationView);

    //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {


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

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

            //Check to see which item was clicked and perform the appropriate action.
            switch (menuItem.getItemId()) {

                case R.id.posts:
                    PostListFragmentWebView postListFragment = new PostListFragmentWebView();
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.frame, postListFragment)
                            .commit();
                    return true;

                case R.id.pages:
                    PageListFragmentWebView pagetListFragment = new PageListFragmentWebView();
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.frame, pagetListFragment)
                            .commit();
                    return true;

                case R.id.blog:
                    BlogInfoFragmentWebView blogInfoFragment = new BlogInfoFragmentWebView();
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.frame, blogInfoFragment)
                            .commit();
                    return true;

                default:
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.drawer_error), Toast.LENGTH_SHORT).show();
                    return true;

            }

        }
    });

    // Initializing Drawer Layout and ActionBarToggle
    drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_drawer, R.string.close_drawer) {

        @Override
        public void onDrawerClosed(View drawerView) {
            // Code here will be triggered once the drawer closes as we don't want anything to happen so we leave this blank.
            super.onDrawerClosed(drawerView);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank.

            super.onDrawerOpened(drawerView);
        }
    };

    //Setting the actionbarToggle to drawer layout
    drawerLayout.setDrawerListener(actionBarDrawerToggle);
    drawerLayout.getChildAt(0).setSelected(true);

    //calling sync state is necessary or else your hamburger icon wont show up
    actionBarDrawerToggle.syncState();
}
}
Hathor answered 25/6, 2015 at 6:53 Comment(4)
have you tried to call navigationView.getMenu().findItem(menuItemId).setChecked(true)Homomorphism
This just marks the item as selected I already did this in xml..Hathor
getMenu from navigationView and then call performIdentifierActionHomomorphism
Possible duplicate of Navigation drawer: How do I set the selected item at startup?Fredericksburg
H
45

In onCreate(), following code will load the first item's fragment upon first start:

if (savedInstanceState == null) {
    navigationView.getMenu().performIdentifierAction(R.id.posts, 0);
}

Thanks to calvinfly for this comment.

Hathor answered 25/6, 2015 at 8:23 Comment(3)
Where did you put this code to make sure it only runs on start, and not every time the activity is created?Rivy
Also, this selects the first item but doesn't mark it as checked inside the menu. :/Rivy
I have put it in onCreate, for item checking if (menuItem.isChecked()) menuItem.setChecked(false); else menuItem.setChecked(true); worked for me. BTW I am no longer using this instead I am now using THIS libraryHathor
D
17

Add android:checked="true" to your first menu item.

And manually select one item, using

getSupportFragmentManager().beginTransaction().replace(R.id.frame, postListFragment).commit();

to open fragment.

Decolorize answered 25/6, 2015 at 6:57 Comment(2)
its already added but when activity starts it shows blank page i.e. activities content view I want to replace that with fragment, I know I can directly do this with FragmentTransaction but I want to select first navigation item in drawer programatically!Hathor
Add android:checked="true" just make menu have selected state. And see my revised answer to open fragment.Decolorize
D
5

Instead of normal listener ...

navView.setNavigationItemSelected(new Navigation.View.OnNavigationItemSelectedListener() {bla, bla, bla})

Create the listener as an Obj:

NavigationView.OnNavigationItemSelectedListener navViewListener;
            navView.setNavigationItemSelectedListener(navViewListener = new NavigationView.OnNavigationItemSelectedListener() {bla, bla, bla})

...and use the Obj to trigger the listener event:

navViewListener.onNavigationItemSelected(navView.getMenu().getItem(0));

...where getItem(0) is the first menu item.

Use a method getItem(0).setChecked(true) or android:checked="true" at its menu item XML definition.

Delectation answered 13/4, 2016 at 14:30 Comment(1)
perfect solution!Nomothetic
L
1

You could also use navigationView.setCheckedItem(R.id.default)(javadoc) after you setup your navigationview.

Leeward answered 2/3, 2016 at 1:44 Comment(0)
I
0

just add this code in onCreate method:

FragmentTransaction ftrans = getFragmentManager().beginTransaction();
ftrans.replace(R.id.container, <yourfragment>).commit();

Work for me !

Iridotomy answered 21/6, 2016 at 11:53 Comment(0)
S
0

This can be done even better while considering orientation and other configuration changes. We could select whatever nav drawer menuitem depending on whether we are coming from a previous state. Check: For the Navigation drawer wielding Activity:-

public static final String SELECTED_NAV_MENU_KEY = "selected_nav_menu_key";
// The selected grid position
private int mSelectedNavMenuIndex = 0;

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

   ...........................................................

    navigationView.setNavigationItemSelectedListener(this);

    if (savedInstanceState != null) {
        // Recover assets
        mSelectedNavMenuIndex = savedInstanceState.getInt(SELECTED_NAV_MENU_KEY);

        // Recover menu as selected
        MenuItem menuItem = navigationView.getMenu().getItem(mSelectedNavMenuIndex);
        toggleNavMenuItemCheck(menuItem);
        navigationView.getMenu().performIdentifierAction(menuItem.getItemId(), mSelectedNavMenuIndex);
        return;
    } else {
        MenuItem menuItem = navigationView.getMenu().getItem(mSelectedNavMenuIndex);
        toggleNavMenuItemCheck(menuItem);
        navigationView.getMenu().performIdentifierAction(menuItem.getItemId(), mSelectedNavMenuIndex);
    }
}

The toggle method that helps uncheck or check the menu item

private void toggleNavMenuItemCheck(MenuItem menuItem) {
    if (menuItem.isChecked()){
        menuItem.setChecked(false);
    }  else {
        menuItem.setChecked(true);
    }
}

This is how I save the state of the selected menu item. Check:-

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

        switch (id) {
            case R.id.nav_explore:
                showExploreFragment(null);
                mSelectedNavMenuIndex = 0;
                break;
            case R.id.nav_orders:
                mSelectedNavMenuIndex = 1;
                break;
            case R.id.nav_settings:
                mSelectedNavMenuIndex = 2;
                break;
            default:
                showExploreFragment(null);
                mSelectedNavMenuIndex = 0;
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

// Save any important data for recovery
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(SELECTED_NAV_MENU_KEY, mSelectedNavMenuIndex);
    }

NB: The line with code:

navigationView.getMenu().performIdentifierAction(menuItem.getItemId(), mSelectedNavMenuIndex);

Can be replaced by the code:

onNavigationItemSelected(menuItem);
Sacchariferous answered 4/7, 2016 at 5:43 Comment(0)
S
0

in menu.xml remember to mention android:checkable="true" for single item and android:checkableBehavior="single" for a group of items.

<item
        android:id="@+id/pos_item_help"
        android:checkable="true"
        android:title="Help" />

    <group
        android:id="@+id/group"
        android:checkableBehavior="single">
        <item
            android:id="@+id/menu_nav_home"
            android:icon="@drawable/ic_home_black_24dp"
            android:title="@string/menu_nav_home" />
    </group>

then inside NavigationItemSelectedListener use setCheckedItem(R.id.item_id_in_menu) to make it selected.

@Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {

            case R.id.pos_item_pos:
                navigationView.setCheckedItem(R.id.pos_item_pos);
                break;
            case R.id.pos_item_orders:
                navigationView.setCheckedItem(R.id.pos_item_orders);
                break;
            default:
        }
        return true;
    }

And you do not have to do the dirty task of managing the selected item anymore. navigationView manages it by self.

Singleton answered 12/6, 2017 at 10:6 Comment(0)
B
0

1.) To land to the HomeFragment initially, use this inside your onCreate() in MainActivity:

Fragment fragment = new HomeFragment();
// replacing the fragment
if (fragment != null) {
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.content_frame, fragment);
    ft.commit();
}

2.) To set the item as selected in navigationDrawer set the item as checked in navigation_menu.xml

 android:checked = "true"
Burnejones answered 15/10, 2017 at 14:8 Comment(0)
H
0

I think better to set the

app:startDestination="@+id/nav_item"

To choose first NavigationView.

Harvestman answered 27/4, 2023 at 8:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.