如今App的UI設計中Drawerlayout+NavigationView是一個比較經常使用的設計了,而之前我通常只是在Navigation中的menu(即下部的item中)添加事件監聽,而今天碰到一個須要是要在header中增長事件監聽。android
需求以下:點擊圖片,在底部彈出一個彈出窗口。app
側邊導航欄佈局:ide
<!--側邊導航欄--> <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.circleimageview.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>
那顯然咱們得要獲取到這個image的id,從而給它設置點擊事件監聽。佈局
然而,當我用ButterKnife去綁定它的時候,直接就報錯了this
也對,這個時候側邊欄尚未打開spa
接下來我就想着要在側邊欄打開的狀況下去獲取到這個id,怎麼監聽側邊欄是否打開呢,我嘗試了這個方法設計
(竊喜),在onDrawerOpened中寫入進行一波findViewById操做應該就能夠了吧。3d
然並卵。。。code
點擊頭像毫無反應。xml
最後,那咱們就不在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(); } });
最終的效果圖:
最後徵求更好的方法有木有!有的話請砸過來~!