Search code examples
android-studiokotlinfindviewbyid

findViewById() unresolved reference in codelabs


Good day, y'all! Today I was doing the Google Codelabs for Kotlin. I'm trying to use findViewById() in a function but it shows as an unresolved reference. I bet it's a fairly easy problem but I can't figure it out. this is my code

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    findViewById<Button>(R.id.done_button).setOnClickListener { addNickname(it) }
}
}

private fun addNickname(view: View) {
val editText = findViewById<EditText>(R.id.nickname_edit)
val nicknameTextView = findViewById<TextView>(R.id.nickname_text)
nicknameTextView.text = editText.text
nicknameTextView.visibility = View.VISIBLE
editText.visibility = View.GONE
view.visibility = View.GONE
}

When I try to assign the editText and the nickmaneTextView vals to the views I use findViewById() but it shows as unresolved reverence. it's quite basic so I don't know where is the issue

I'll be very grateful for your help

Edit: if I use

val editText = view.findViewById<EditText>(R.id.nickname_edit)
val nicknameTextView = view.findViewById<TextView>(R.id.nickname_text)

I get an error saying that the nicknameTextView is null and it crashes


Solution

  • Ok I figured it out, the fun must be created inside the

    class MainActivity: AppCompatActivity() {
      override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      }
    'here'
    }
    

    I knew it was a dumb problem :(

    Thank you for your help