现在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();
}
});
最终的效果图:
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。