Android NavigationView头部设置监听事件
NavigationView头部设置监听事件的方法,供大家参考,具体内容如下
1、将XML里的静态引入删除:
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); //获取头部布局 ViewnavHeaderView=navigationView.getHeaderView(0);
3、完整代码如下:
privatevoidinitNavigation(){ 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(newNavigationView.OnNavigationItemSelectedListener(){ @Override publicbooleanonNavigationItemSelected(@NonNullMenuItemitem){ switch(item.getItemId()){ caseR.id.add_city: //启动 startActivityForResult(newIntent(MainActivity.this,CityPickerActivity.class), REQUEST_CODE_PICK_CITY); drawerLayout.closeDrawers(); break; caseR.id.setting: IntentSettingIntent=newIntent(MainActivity.this,SettingActivity.class); startActivity(SettingIntent); drawerLayout.closeDrawers(); break; caseR.id.about: IntentaboutIntent=newIntent(MainActivity.this,aboutActivity.class); startActivity(aboutIntent); drawerLayout.closeDrawers(); break; } returnfalse; } }); //获取头部布局 ViewnavHeaderView=navigationView.getHeaderView(0); //设置监听事件 icon_image=(CircleImageView)navHeaderView.findViewById(R.id.icon_image); icon_image.setOnClickListener(newView.OnClickListener(){ @Override publicvoidonClick(Viewview){ dialog.show(); } }); //读取头像 Utility.getImageFromShare(this,icon_image); //dialog dialog=newCustomDialog(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(newView.OnClickListener(){ @Override publicvoidonClick(Viewview){ toCamera(); } }); btn_picture=(Button)dialog.findViewById(R.id.btn_picture); btn_picture.setOnClickListener(newView.OnClickListener(){ @Override publicvoidonClick(Viewview){ toPicture(); } }); btn_cancel=(Button)dialog.findViewById(R.id.btn_cancel); btn_cancel.setOnClickListener(newView.OnClickListener(){ @Override publicvoidonClick(Viewview){ dialog.dismiss(); } }); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。