java - Built-in Navigation Drawer Activity (on click event) -
i decided make application uses navigation drawer. created app. using built-in navigation drawer activity ( android studio ) make idea of contains, launched on phone.it works smooth but, want new activity show when press on item drawer panel. how do that?
this mainactivity.java
import android.app.activity; import android.app.actionbar; import android.app.fragment; import android.app.fragmentmanager; import android.content.context; import android.os.build; import android.os.bundle; import android.view.gravity; import android.view.layoutinflater; import android.view.menu; import android.view.menuitem; import android.view.view; import android.view.viewgroup; import android.support.v4.widget.drawerlayout; import android.widget.arrayadapter; import android.widget.textview; public class mainactivity extends activity implements navigationdrawerfragment.navigationdrawercallbacks { /** * fragment managing behaviors, interactions , presentation of navigation drawer. */ private navigationdrawerfragment mnavigationdrawerfragment; /** * used store last screen title. use in {@link #restoreactionbar()}. */ private charsequence mtitle; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); mnavigationdrawerfragment = (navigationdrawerfragment) getfragmentmanager().findfragmentbyid(r.id.navigation_drawer); mtitle = gettitle(); // set drawer. mnavigationdrawerfragment.setup( r.id.navigation_drawer, (drawerlayout) findviewbyid(r.id.drawer_layout)); } @override public void onnavigationdraweritemselected(int position) { // update main content replacing fragments fragmentmanager fragmentmanager = getfragmentmanager(); fragmentmanager.begintransaction() .replace(r.id.container, placeholderfragment.newinstance(position + 1)) .commit(); } public void onsectionattached(int number) { switch (number) { case 1: mtitle = getstring(r.string.title_section1); break; case 2: mtitle = getstring(r.string.title_section2); break; case 3: mtitle = getstring(r.string.title_section3); break; case 4: mtitle = getstring(r.string.title_section4); break; } } public void restoreactionbar() { actionbar actionbar = getactionbar(); actionbar.setnavigationmode(actionbar.navigation_mode_standard); actionbar.setdisplayshowtitleenabled(true); actionbar.settitle(mtitle); } @override public boolean oncreateoptionsmenu(menu menu) { if (!mnavigationdrawerfragment.isdraweropen()) { // show items in action bar relevant screen // if drawer not showing. otherwise, let drawer // decide show in action bar. getmenuinflater().inflate(r.menu.main, menu); restoreactionbar(); return true; } return super.oncreateoptionsmenu(menu); } @override public boolean onoptionsitemselected(menuitem item) { // handle action bar item clicks here. action bar // automatically handle clicks on home/up button, long // specify parent activity in androidmanifest.xml. int id = item.getitemid(); //noinspection simplifiableifstatement if (id == r.id.action_settings) { return true; } return super.onoptionsitemselected(item); } /** * placeholder fragment containing simple view. */ public static class placeholderfragment extends fragment { /** * fragment argument representing section number * fragment. */ private static final string arg_section_number = "section_number"; /** * returns new instance of fragment given section * number. */ public static placeholderfragment newinstance(int sectionnumber) { placeholderfragment fragment = new placeholderfragment(); bundle args = new bundle(); args.putint(arg_section_number, sectionnumber); fragment.setarguments(args); return fragment; } public placeholderfragment() { } @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view rootview = inflater.inflate(r.layout.fragment_main, container, false); return rootview; } @override public void onattach(activity activity) { super.onattach(activity); ((mainactivity) activity).onsectionattached( getarguments().getint(arg_section_number)); } } }
here's navigationdrawerfragment.java:
import android.app.activity; import android.app.actionbar; import android.app.fragment; import android.support.v4.app.actionbardrawertoggle; import android.support.v4.view.gravitycompat; import android.support.v4.widget.drawerlayout; import android.content.sharedpreferences; import android.content.res.configuration; import android.os.bundle; import android.preference.preferencemanager; import android.view.layoutinflater; import android.view.menu; import android.view.menuinflater; import android.view.menuitem; import android.view.view; import android.view.viewgroup; import android.widget.adapterview; import android.widget.arrayadapter; import android.widget.listview; import android.widget.toast; /** * fragment used managing interactions , presentation of navigation drawer. * see <a href="https://developer.android.com/design/patterns/navigation-drawer.html#interaction"> * design guidelines</a> complete explanation of behaviors implemented here. */ public class navigationdrawerfragment extends fragment { /** * remember position of selected item. */ private static final string state_selected_position = "selected_navigation_drawer_position"; /** * per design guidelines, should show drawer on launch until user manually * expands it. shared preference tracks this. */ private static final string pref_user_learned_drawer = "navigation_drawer_learned"; /** * pointer current callbacks instance (the activity). */ private navigationdrawercallbacks mcallbacks; /** * helper component ties action bar navigation drawer. */ private actionbardrawertoggle mdrawertoggle; private drawerlayout mdrawerlayout; private listview mdrawerlistview; private view mfragmentcontainerview; private int mcurrentselectedposition = 0; private boolean mfromsavedinstancestate; private boolean muserlearneddrawer; public navigationdrawerfragment() { } @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); // read in flag indicating whether or not user has demonstrated awareness of // drawer. see pref_user_learned_drawer details. sharedpreferences sp = preferencemanager.getdefaultsharedpreferences(getactivity()); muserlearneddrawer = sp.getboolean(pref_user_learned_drawer, false); if (savedinstancestate != null) { mcurrentselectedposition = savedinstancestate.getint(state_selected_position); mfromsavedinstancestate = true; } // select either default item (0) or last selected item. selectitem(mcurrentselectedposition); } @override public void onactivitycreated(bundle savedinstancestate) { super.onactivitycreated(savedinstancestate); // indicate fragment influence set of actions in action bar. sethasoptionsmenu(true); } @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { mdrawerlistview = (listview) inflater.inflate( r.layout.fragment_navigation_drawer, container, false); mdrawerlistview.setonitemclicklistener(new adapterview.onitemclicklistener() { @override public void onitemclick(adapterview<?> parent, view view, int position, long id) { selectitem(position); } }); mdrawerlistview.setadapter(new arrayadapter<string>( getactionbar().getthemedcontext(), android.r.layout.simple_list_item_activated_1, android.r.id.text1, new string[]{ getstring(r.string.title_section1), getstring(r.string.title_section2), getstring(r.string.title_section3), getstring(r.string.title_section4), })); mdrawerlistview.setitemchecked(mcurrentselectedposition, true); return mdrawerlistview; } public boolean isdraweropen() { return mdrawerlayout != null && mdrawerlayout.isdraweropen(mfragmentcontainerview); } /** * users of fragment must call method set navigation drawer interactions. * * @param fragmentid android:id of fragment in activity's layout. * @param drawerlayout drawerlayout containing fragment's ui. */ public void setup(int fragmentid, drawerlayout drawerlayout) { mfragmentcontainerview = getactivity().findviewbyid(fragmentid); mdrawerlayout = drawerlayout; // set custom shadow overlays main content when drawer opens mdrawerlayout.setdrawershadow(r.drawable.drawer_shadow, gravitycompat.start); // set drawer's list view items , click listener actionbar actionbar = getactionbar(); actionbar.setdisplayhomeasupenabled(true); actionbar.sethomebuttonenabled(true); // actionbardrawertoggle ties the proper interactions // between navigation drawer , action bar app icon. mdrawertoggle = new actionbardrawertoggle( getactivity(), /* host activity */ mdrawerlayout, /* drawerlayout object */ r.drawable.ic_drawer, /* nav drawer image replace 'up' caret */ r.string.navigation_drawer_open, /* "open drawer" description accessibility */ r.string.navigation_drawer_close /* "close drawer" description accessibility */ ) { @override public void ondrawerclosed(view drawerview) { super.ondrawerclosed(drawerview); if (!isadded()) { return; } getactivity().invalidateoptionsmenu(); // calls onprepareoptionsmenu() } @override public void ondraweropened(view drawerview) { super.ondraweropened(drawerview); if (!isadded()) { return; } if (!muserlearneddrawer) { // user manually opened drawer; store flag prevent auto-showing // navigation drawer automatically in future. muserlearneddrawer = true; sharedpreferences sp = preferencemanager .getdefaultsharedpreferences(getactivity()); sp.edit().putboolean(pref_user_learned_drawer, true).apply(); } getactivity().invalidateoptionsmenu(); // calls onprepareoptionsmenu() } }; // if user hasn't 'learned' drawer, open introduce them drawer, // per navigation drawer design guidelines. if (!muserlearneddrawer && !mfromsavedinstancestate) { mdrawerlayout.opendrawer(mfragmentcontainerview); } // defer code dependent on restoration of previous instance state. mdrawerlayout.post(new runnable() { @override public void run() { mdrawertoggle.syncstate(); } }); mdrawerlayout.setdrawerlistener(mdrawertoggle); } private void selectitem(int position) { mcurrentselectedposition = position; if (mdrawerlistview != null) { mdrawerlistview.setitemchecked(position, true); } if (mdrawerlayout != null) { mdrawerlayout.closedrawer(mfragmentcontainerview); } if (mcallbacks != null) { mcallbacks.onnavigationdraweritemselected(position); } } @override public void onattach(activity activity) { super.onattach(activity); try { mcallbacks = (navigationdrawercallbacks) activity; } catch (classcastexception e) { throw new classcastexception("activity must implement navigationdrawercallbacks."); } } @override public void ondetach() { super.ondetach(); mcallbacks = null; } @override public void onsaveinstancestate(bundle outstate) { super.onsaveinstancestate(outstate); outstate.putint(state_selected_position, mcurrentselectedposition); } @override public void onconfigurationchanged(configuration newconfig) { super.onconfigurationchanged(newconfig); // forward new configuration drawer toggle component. mdrawertoggle.onconfigurationchanged(newconfig); } @override public void oncreateoptionsmenu(menu menu, menuinflater inflater) { // if drawer open, show global app actions in action bar. see // showglobalcontextactionbar, controls top-left area of action bar. if (mdrawerlayout != null && isdraweropen()) { inflater.inflate(r.menu.global, menu); showglobalcontextactionbar(); } super.oncreateoptionsmenu(menu, inflater); } @override public boolean onoptionsitemselected(menuitem item) { if (mdrawertoggle.onoptionsitemselected(item)) { return true; } if (item.getitemid() == r.id.action_example) { toast.maketext(getactivity(), "example action.", toast.length_short).show(); return true; } return super.onoptionsitemselected(item); } /** * per navigation drawer design guidelines, updates action bar show global app * 'context', rather what's in current screen. */ private void showglobalcontextactionbar() { actionbar actionbar = getactionbar(); actionbar.setdisplayshowtitleenabled(true); actionbar.setnavigationmode(actionbar.navigation_mode_standard); actionbar.settitle(r.string.app_name); } private actionbar getactionbar() { return getactivity().getactionbar(); } /** * callbacks interface activities using fragment must implement. */ public static interface navigationdrawercallbacks { /** * called when item in navigation drawer selected. */ void onnavigationdraweritemselected(int position); } }
and activity_main.xml:
<android.support.v4.widget.drawerlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mainactivity"> <framelayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" /> <fragment android:id="@+id/navigation_drawer" android:layout_width="@dimen/navigation_drawer_width" android:layout_height="match_parent" android:layout_gravity="start" android:name="com.alec.drawertest.navigationdrawerfragment" tools:layout="@layout/fragment_navigation_drawer" /> </android.support.v4.widget.drawerlayout>
this code of yours listens click event:
mdrawerlistview.setonitemclicklistener(new adapterview.onitemclicklistener() { @override public void onitemclick(adapterview<?> parent, view view, int position, long id) { selectitem(position); } });
position item no. of navigation drawer item clicked. can use switch case identify item clicked , call startactivity using
intent intent = new intent(this, displaymessageactivity.class); startactivity(intent);
your selectitem should this:
private void selectitem(int position) { intent intent; switch (position) { case 0: intent = new intent(currentactivity, newactivity.class); intent.addflags(intent.flag_activity_clear_top); currentactivity.startactivity(intent); break; case 1: // etc.
Comments
Post a Comment