In my activity, I am inflating the layout via data binding. The binding itself works correctly, and I am able to get references to objects in the layout file easily.
One of those objects is a NavigationView
. It has a headerLayout
:
<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:background="@android:color/white"
android:fitsSystemWindows="true"
app:itemIconTint="@color/navigation_view_color"
app:itemTextColor="@color/navigation_view_color"
app:headerLayout="@layout/nav_view_header" />
The header layout looks like this (extra objects removed for simplicity):
<androidx.constraintlayout.widget.ConstraintLayout
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="wrap_content"
android:background="@color/menu_blue"
android:paddingBottom="32dp">
<ImageView
android:id="@+id/navViewLogOutButton"
android:layout_width="48dp"
android:layout_height="48dp"
android:padding="12dp"
android:src="@drawable/logout"
app:tint="@color/white"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="16dp"
android:contentDescription="@string/sz.proApp.support.logOut" />
</androidx.constraintlayout.widget.ConstraintLayout>
I need to set a click listener on this image view, but I can't get a reference to it. This is what I am using:
binding.navView.findViewById<ImageView>(R.id.navViewLogOutButton)?.setOnClickListener{
doSomething()
}
I've verified that binding.navView
is not null
. Also, by setting a break point there, I can see what the memory address for this ImageView
is. When I change that line to this:
binding.navView.findViewById<ImageView>(213123403)
I get the reference that I want. But obviously, I can't just use the integer since that is dynamic. The code compiles and the app launches. But when it hits that line, findViewById
returns null every time.
I read that findViewById
may not work with data binding in a activity, but if that is true, then how can I get this reference so that I can set the listener?
app:headerLayout="@layout/nav_view_header"
So, the generated binding class should beNavViewHeaderBinding
, you can get the binding with:
val headerBinding = NavViewHeaderBinding.bind(binding.navView.getHeaderView(0))
And access the header views through headerBinding
:
headerBinding.navViewLogOutButton
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With