问题
I have such variant, but I believe that there is a better way to do this
val header = nav_view.getHeaderView(0) as LinearLayout
val userName = header.findViewById(R.id.user_name) as TextView
The issue is that when I try to get it just by user_name
, it is null
.
回答1:
This might help you and i think that its better way .
nav_view.getHeaderView(0).userNameTxt.text
This is shortest way to access from header.
回答2:
You might consider using Android-Kotlin extension plugin. In that case your code will be much simpler and would be:
val headerView: View = nav_view.getHeaderView(0)
headerView.userNameTxt.text = "Some Value"
来源:https://stackoverflow.com/questions/47097846/kotlin-get-view-from-navigationview-header