Kotlin获取NavigationView头布局中的控件报空指针[通俗易懂]

(60) 2023-08-02 17:12

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说Kotlin获取NavigationView头布局中的控件报空指针[通俗易懂],希望能够帮助你!!!。

在kotlin中,你不需要findViewById()来获取到控件,然后对其进行操作,只需要通过静态布局引入就可以通过对应的id进行操作了,但是并不代表你可以随意的使用,比如说获取NavigationView中的头布局里面的控件,你需要通过NavigationView获取HeaderView然后才能拿到他的子View了

示例代码

主布局代码

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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" />
 <com.google.android.material.navigation.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" />
</androidx.drawerlayout.widget.DrawerLayout>

头布局代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:id="@+id/ll_user_info"
 android:layout_width="match_parent"
 android:layout_height="@dimen/nav_header_height"
 android:layout_gravity="center_horizontal"
 android:background="@drawable/side_nav_bar"
 android:gravity="bottom|center_horizontal"
 android:orientation="vertical"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:theme="@style/ThemeOverlay.AppCompat.Dark">
 <ImageView
 android:id="@+id/imageView"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:contentDescription="@string/nav_header_desc"
 android:paddingTop="@dimen/nav_header_vertical_spacing"
 app:srcCompat="@mipmap/ic_launcher_round" />
 <TextView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:gravity="center_horizontal"
 android:paddingTop="@dimen/nav_header_vertical_spacing"
 android:text="@string/nick_name"
 android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
 <TextView
 android:id="@+id/textView"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="@string/signature" />
</LinearLayout>

逻辑代码

//用户资料
nav_view.getHeaderView(0).ll_user_info.setOnClickListener {
 startActivity(Intent(this@MainActivity,UserHomeActivity::class.java))
}

至于其中getHeaderView索引为什么是0,我查了很多资料,说一般头布局基本上都是0号元素,所以填写0

上一篇

已是最后文章

下一篇

已是最新文章

发表回复