Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a view from layout specified in headerLayout of NavigationView using Kotlin in Android

I want to access a TextView which is included inside headerLayout of NavigationView. Is it possible to access the view using Kotlin android extension? I did using this method, but the TextView (here txtName) is always null.

Here is my activity_main.xml

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

nav_header_splash.xml

<TextView
    android:id="@+id/txtName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@+id/txt1"
    android:layout_below="@+id/imageView"
    android:text="@string/name"
    android:textSize="18sp"
    android:textColor="@color/white" />

in MainActivity.kt I have imported

import kotlinx.android.synthetic.main.nav_header_splash.*

in onCreate() of Activity class I set text like

txtName.text = "Sample Code"

build.gradle of app folder

apply plugin: 'kotlin-android-extensions'

build.gradle of my project

 classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"

Is there any mistake in my code? Please help. I'm new in Kotlin.

like image 403
Sandra Avatar asked Dec 06 '17 08:12

Sandra


1 Answers

Do not import kotlinx.android.synthetic.main.nav_header_splash.* it will be available from the main file itself as

instead import kotlinx.android.synthetic.main.nav_header_splash.view.*

and get view by using

val header = mNavigationView.getHeaderView(0)
header.txtName.text = "Sample Code"
like image 65
Irony Stack Avatar answered Nov 22 '22 19:11

Irony Stack