现在App的UI设计中Drawerlayout+NavigationView是一个比较常用的设计了,而以前我一般只是在Navigation中的menu(即下部的item中)添加事件监听,而今天碰到一个需要是要在header中增加事件监听。

  需求如下:点击图片,在底部弹出一个弹出窗口。

  

   侧边导航栏布局:

复制代码

 <!--侧边导航栏-->
    <android.support.design.widget.NavigationView        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/menu_nav"
        />

复制代码

复制代码

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="180dp"
    android:padding="10dp"
    android:background="?attr/colorPrimary">

    <de.hdodenhof.circlep_w_picpathview.CircleImageView        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/account"
        android:src="@drawable/ic_account"
        android:layout_centerInParent="true" />
    <TextView        android:id="@+id/qianming"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerInParent="true"
        android:textSize="16sp"
        android:text="学好英语走遍天下"
         /></RelativeLayout>

复制代码

  那显然我们得要获取到这个p_w_picpath的id,从而给它设置点击事件监听。

  然而,当我用ButterKnife去绑定它的时候,直接就报错了

也对,这个时候侧边栏还没有打开

  接下来我就想着要在侧边栏打开的情况下去获取到这个id,怎么监听侧边栏是否打开呢,我尝试了这个方法

  (窃喜),在onDrawerOpened中写入进行一波findViewById操作应该就可以了吧。

  然并卵。。。

  点击头像毫无反应。

  最后,那我们就不在xml中静态导入header了还不行吗,我们直接在代码中直接导入header的布局,然后再来获取它里面图片的id,并为其设置事件监听,终于KO。

此处需要删除原先的这一行:

app:headerLayout="@layout/nav_header_main"

复制代码

 <!--侧边导航栏-->
    <android.support.design.widget.NavigationView        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        
        app:menu="@menu/menu_nav"
        />

复制代码

onCreate()中加入下面代码:

复制代码

 View drawerView = navigationView.inflateHeaderView(R.layout.nav_header_main);
        CircleImageView account = (CircleImageView) drawerView.findViewById(R.id.account);
        account.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                bottomPopupOption = new BottomPopupOption(TabHostActivity.this);
                bottomPopupOption.setItemText("拍照","选择相册");
                bottomPopupOption.showPopupWindow();
            }
        });

复制代码

最终的效果图: