如何在headerLayout android kotlin中查找视图

时间:2017-08-10 09:10:52

标签: android kotlin

我在main_activity中有NavagationView,在NavagationView中有一个headerLayout main_activity

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />

nav_header_main

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:gravity="bottom"
android:orientation="horizontal"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">

<ImageView
    android:id="@+id/avatar"
    android:layout_width="96dp"
    android:layout_height="96dp"
    android:layout_margin="@dimen/nav_header_vertical_spacing"
    app:srcCompat="@drawable/logo" />

` 问题是如何在主要活动中找到头像图像 我尝试 avatar.setOnClickListener {} 但抛出NulPointer异常 我也导入了这个 import kotlinx.android.synthetic.main.nav_header_main。

2 个答案:

答案 0 :(得分:0)

import kotlinx.android.synthetic.main.nav_header_main.*

您错过了*。并确保您事先调用setContentView。

setContentView(R.layout.activity_main)

答案 1 :(得分:0)

val navigationView: NavigationView = findViewById(R.id.nav_view)
//if your kotlin version less 1.1.4-2 then as as NavigationView

val header = navigation_view.getHeaderView(0)
val avatar: ImageView = header.findViewById(R.id.avatar)
avatar.setOnClickListener {
    //do something 
}