findViewById in Kotlin

2

I was generating an action by clicking on a Button

fun cliqueBotao(view : View){
    var texto = findViewById<>(R.id.textoExibicao) as TextView
    texto.setText("Texto alterado")
}

Only Android Studio complained that findViewById<> is without parameter. I did a quick search and noticed that some methods put the value passed by parameter when the method is created fun cliqueBotao(view : View) within findViewById<>

And my method stayed like this

fun cliqueBotao(view : View){
    var texto = findViewById<View>(R.id.textoExibicao) as TextView
    texto.setText("Texto alterado")
}

So far my App is working normal, why before did not need and now needs and this form is correct?

Thank you in advance

    
asked by anonymous 07.01.2018 / 01:14

2 answers

4
  

Forget the FindViewById:)

Using "Extensions" you no longer need to use findViewbyId in Kotlin. You can access your views using the ID directly. It's simple:

1 - In gradle, add the plugin:

apply plugin: 'kotlin-android-extensions'

2 - In your Activity do the import (Assume that we are in the Main Activity):

import kotlinx.android.synthetic.main.activity_main.*

And that's it. You can do this:

textoExibicao.setText("Texto alterado")

:)

    
19.01.2018 / 12:08
2

This is happening because you are forcing the type of findViewById when it does as TextView . Since API 26, this is no longer necessary-- the type is automatically inferred for you.

So you can do just this:

var texto = findViewById(R.id.textoExibicao)
texto.setText("Texto alterado")

or better yet:

val texto = findViewById(R.id.textoExibicao)
texto.text = "Texto alterado"
    
07.01.2018 / 04:47