1. 程式人生 > >NavigationView的頭部的事件監聽

NavigationView的頭部的事件監聽

navig

現在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.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去綁定它的時候,直接就報錯了

技術分享

也對,這個時候側邊欄還沒有打開

  接下來我就想著要在側邊欄打開的情況下去獲取到這個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();
            }
        });

技術分享

最終的效果圖:

技術分享


NavigationView的頭部的事件監聽