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();
}
}); }
上一篇:第29讲 UI组件之 ListView与 BaseAdapter,SimpleAdapter


下一篇:Oracle高级查询之CONNECT BY