Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access EditText or other UI components with Kotlin

I'm using Android Studio 3.0 RC2 & Kotlin.

When I try to access a UI component the app crashes unless I first write findViewById. I thought Kotlin was supposed to get rid of having to write findViewById line? The UI is a fragment and I'm trying to access from the same fragment code. Is there a way to not have to write findViewById?

These lines work:

var userNameField = view?.findViewById<EditText>(R.id.userNameTextField) as EditText
userNameField.setText("hello world")

This line doesn't work without findViewById line

userNameTextField.setText("hello world")

I even have

import kotlinx.android.synthetic.main.fragment_sign_in.*

The onCreateView() code:

 override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
    // Inflate the layout for this fragment
    var view = inflater!!.inflate(R.layout.fragment_sign_in, container, false)

    var userNameField = view?.findViewById<EditText>(R.id.userNameTextField) as EditText
    userNameField.setText("hello world")

    return view
}
like image 946
user1184205 Avatar asked Oct 23 '17 05:10

user1184205


2 Answers

In the onCreateView just return the inflated view.

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
    // Inflate the layout for this fragment
return inflater!!.inflate(R.layout.fragment_sign_in, container, false)

}

In the onViewCreated you can access your view components

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        userNameField.setText("hello world")
    }
like image 196
Fredy Mederos Avatar answered Nov 04 '22 23:11

Fredy Mederos


I was brought here by searching for the same issue. I missed to add the kotlin-android-extensions to the build.gradle:

apply plugin: 'kotlin-android-extensions'
like image 33
Dirk Hönisch Avatar answered Nov 05 '22 00:11

Dirk Hönisch