android - Navigation drawer: How do I set the selected item at startup? -
my code works perfectly: every time item in navigation drawer clicked item selected.
of course want start app default fragment (home), navigation drawer doesn't have item selected. how can select item programmatically?
public class baseapp extends appcompatactivity { //defining variables protected string logtag = "logdebug"; protected toolbar toolbar; protected navigationview navigationview; protected drawerlayout drawerlayout; private datemanager db = null; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.base_layout); navigationview = (navigationview) findviewbyid(r.id.navigation_view); // set home/dashboard @ startup fragmenttransaction fragmenttransaction = getsupportfragmentmanager().begintransaction(); fragmenttransaction.replace(r.id.frame, new dashboardfragment()); fragmenttransaction.commit(); setnavdrawer(); } private void setnavdrawer(){ // initializing toolbar , setting actionbar toolbar = (toolbar) findviewbyid(r.id.toolbar); setsupportactionbar(toolbar); //initializing navigationview //setting navigation view item selected listener handle item click of navigation menu navigationview.setnavigationitemselectedlistener(new navigationview.onnavigationitemselectedlistener() { // method trigger on item click of navigation menu @override public boolean onnavigationitemselected(menuitem menuitem) { //checking if item in checked state or not, if not make in checked state // think need edit here... if (menuitem.ischecked()) menuitem.setchecked(false); else menuitem.setchecked(true); //closing drawer on item click drawerlayout.closedrawers(); //check see item being clicked , perform appropriate action switch (menuitem.getitemid()) { //replacing main content contentfragment case r.id.home: dashboardfragment dashboardfragment = new dashboardfragment(); fragmenttransaction fragmenttransaction = getsupportfragmentmanager().begintransaction(); fragmenttransaction.replace(r.id.frame, dashboardfragment,"dashboard_fragment"); fragmenttransaction.commit(); return true; [...]
i think need edit here:
if (menuitem.ischecked()) menuitem.setchecked(false); else menuitem.setchecked(true);
or in oncreate
@ app startup fragmenttransaction.
thank support.
use code below:
navigationview.getmenu().getitem(0).setchecked(true);
call method after call setnavdrawer();
the getitem(int index)
method gets menuitem
can call setchecked(true);
on menuitem
, left find out element index default have, , replace 0 index.
you can select(highlight) item calling
onnavigationitemselected(navigationview.getmenu().getitem(0));
here reference link: http://thegeekyland.blogspot.com/2015/11/navigation-drawer-how-set-selected-item.html
edit did not work on nexus 4, support library revision 24.0.0. recommend use
navigationview.setcheckeditem(r.id.nav_item);
answered @kingston below.
Comments
Post a Comment