Android NavigationView头部设置监听事件
程序员文章站
2023-12-17 08:04:16
navigationview头部设置监听事件的方法,供大家参考,具体内容如下
1、将xml里的静态引入删除:
navigationview头部设置监听事件的方法,供大家参考,具体内容如下
1、将xml里的静态引入删除:
<android.support.design.widget.navigationview android:id="@+id/nav_view" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="start" /> <!--删除下面两行--> <!--app:headerlayout="@layout/nav_header"--> <!--app:menu="@menu/nav_menu"-->
2、在代码里 findviewbyid 找到 navigationview,然后引入 header 和 menu,再获取头部布局,最后设置监听事件:
//findviewbyid navigationview = (navigationview) findviewbyid(r.id.nav_view); //引入header和menu navigationview.inflateheaderview(r.layout.nav_header); navigationview.inflatemenu(r.menu.nav_menu); //获取头部布局 view navheaderview = navigationview.getheaderview(0);
3、完整代码如下:
private void initnavigation() { drawerlayout = (drawerlayout) findviewbyid(r.id.drawer_layout); navigationview = (navigationview) findviewbyid(r.id.nav_view); //引入header和menu navigationview.inflateheaderview(r.layout.nav_header); navigationview.inflatemenu(r.menu.nav_menu); //设置menu的监听事件 navigationview.setnavigationitemselectedlistener(new navigationview.onnavigationitemselectedlistener() { @override public boolean onnavigationitemselected(@nonnull menuitem item) { switch (item.getitemid()) { case r.id.add_city: //启动 startactivityforresult(new intent(mainactivity.this, citypickeractivity.class), request_code_pick_city); drawerlayout.closedrawers(); break; case r.id.setting: intent settingintent = new intent(mainactivity.this, settingactivity.class); startactivity(settingintent); drawerlayout.closedrawers(); break; case r.id.about: intent aboutintent = new intent(mainactivity.this, aboutactivity.class); startactivity(aboutintent); drawerlayout.closedrawers(); break; } return false; } }); //获取头部布局 view navheaderview = navigationview.getheaderview(0); //设置监听事件 icon_image = (circleimageview) navheaderview.findviewbyid(r.id.icon_image); icon_image.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { dialog.show(); } }); //读取头像 utility.getimagefromshare(this, icon_image); //dialog dialog = new customdialog(this, 100, 100, r.layout.dialog_photo, r.style.theme_dialog, gravity.bottom, r.style.pop_anim_style); //屏幕外点击无效 dialog.setcancelable(false); btn_camera = (button) dialog.findviewbyid(r.id.btn_camera); btn_camera.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { tocamera(); } }); btn_picture = (button) dialog.findviewbyid(r.id.btn_picture); btn_picture.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { topicture(); } }); btn_cancel = (button) dialog.findviewbyid(r.id.btn_cancel); btn_cancel.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { dialog.dismiss(); } }); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。