如何獲取對 NavigationView Header 中對象的引用

安卓開發

在我的活動中,我通過數據綁定來擴充佈局。綁定本身工作正常,我能夠輕鬆獲取對佈局文件中對象的引用。

其中一個對像是NavigationView. 它有一個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" />

標題佈局如下所示(為簡單起見,刪除了額外的對象):

<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>

我需要在這個圖像視圖上設置一個點擊偵聽器,但我無法得到它的引用。這就是我正在使用的:

binding.navView.findViewById<ImageView>(R.id.navViewLogOutButton)?.setOnClickListener{
    doSomething()
}

我已經確認binding.navView不是null另外,通過在那裡設置斷點,我可以看到它的內存地址ImageView是什麼。當我將該行更改為:

binding.navView.findViewById<ImageView>(213123403)

我得到了我想要的參考。但顯然,我不能只使用整數,因為它是動態的。代碼編譯並啟動應用程序。但是當它碰到那條線時,findViewById每次都返回 null。

我讀到這findViewById可能不適用於活動中的數據綁定,但如果這是真的,那麼我如何獲得此引用以便我可以設置偵聽器?

贊恩
app:headerLayout="@layout/nav_view_header"

因此,生成的綁定類應該是NavViewHeaderBinding,您可以通過以下方式獲取綁定:

val headerBinding = NavViewHeaderBinding.bind(binding.navView.getHeaderView(0))

並通過headerBinding以下方式訪問標題視圖

headerBinding.navViewLogOutButton

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章