NavigationView的頭部的事件監聽


  現在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();
            }
        });

最終的效果圖:

 

  最后征求更好的方法有木有!有的話請砸過來~!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM