Search code examples
androidkotlinandroid-studio-3.0kotlin-extension

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
}

Solution

  • 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")
        }