NavigationView 中 获得headerView 的点击事件

来源:互联网 发布:淘宝北京聚镁特商贸 编辑:程序博客网 时间:2024/05/29 02:47

MD 中的 菜单控件

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    android:id="@+id/drawer_layout"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:fitsSystemWindows="true">    <android.support.design.widget.CoordinatorLayout        android:id="@+id/main_content"        android:layout_width="match_parent"        android:layout_height="match_parent">        <include            android:id="@+id/appbar"            layout="@layout/toolbar" />        <!--content-->        <include            android:id="@+id/frame_content"            layout="@layout/main_content" />    </android.support.design.widget.CoordinatorLayout>    <!-- navigation-->    <android.support.design.widget.NavigationView        android:id="@+id/navigation_view"        android:layout_width="wrap_content"        android:layout_height="match_parent"        android:layout_gravity="start"        android:background="@drawable/leftm_background"   <div class="line number6 index5 alt1"><code class="java plain">                                        app:headerLayout=</code><code class="java string">"@layout/drawer_header"</code>        app:menu="@menu/menu_navigation" /></div></android.support.v4.widget.DrawerLayout>

 这个样子 会得不到

<code class="java plain">headerLayout</code>
的控件

最近在研究侧滑菜单时发现了一些问题,如果你之前没有接触过肯定会去百度,而我也看了很多demo,相信大家看到的例子都是下面那样布局的

headerLayout加载头布局,menu加载菜单,这样就组成了一个完整的菜单,那么问题来了,menu的点击事件网上都贴出来了,很简单,那么头部呢?你可能会无从下手,那么只有看源码了,NavigationView 中有inflateHeaderView这个方法,看到这个方法你肯定就会觉得是通过这个方法加载头布局,好吧,现在方法有了,但是当你通过这个方法加载时会发现菜单中出现了两个头布局,很显然是加载了两次,第一次就是在布局文件中指定了headerLayout,当你滑动菜单时就会加载这个头布局,第二次是你在代码中又加载了一次。所以会出现两个布局。只要将布局中的headerLayout那行代码删除就可以实现你要的效果。下面给出绑定头部布局的代码


headerLayout加载头布局,menu加载菜单,这样就组成了一个完整的菜单,那么问题来了,menu的点击事件网上都贴出来了,很简单,那么头部呢?你可能会无从下手,那么只有看源码了,NavigationView 中有inflateHeaderView这个方法,看到这个方法你肯定就会觉得是通过这个方法加载头布局,好吧,现在方法有了,但是当你通过这个方法加载时会发现菜单中出现了两个头布局,很显然是加载了两次,第一次就是在布局文件中指定了headerLayout,当你滑动菜单时就会加载这个头布局,第二次是你在代码中又加载了一次。所以会出现两个布局。只要将布局中的headerLayout那行代码删除就可以实现你要的效果。上面是布局内容


红色部分解决问题

//绑定侧滑菜单headerlayout布局, View drawview = nav_view.inflateHeaderView(R.layout.view_leftmenu);ImageView user_pic = (ImageView) drawview.findViewById(R.id.imag_user_pic);



1 0