findViewById no Kotlin

Asked

Viewed 3,854 times

3

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 that Android Studio kept complaining that findViewById<> is no 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 the findViewById<>

And my method was 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, because before needed and now needs and this way is correct?

Thank you in advance

4 answers

8

Forget about Findviewbyid :)

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

1 - In Gradle, add the plugin:

apply plugin: 'kotlin-android-extensions'

2 - In your Activity do import (Suppose we are in Main Activity):

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

That’s it. You can do it like this:

textoExibicao.setText("Texto alterado")

:)

2

This is happening because you’re forcing the kind 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 it just like this:

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

or better yet:

val texto = findViewById(R.id.textoExibicao)
texto.text = "Texto alterado"

1

The plugin kotlin-android-extensions was discontinued. Replace for the Binding view

  1. Remove the plugin kotlin-extensions in the build.gradle (app) and Sincronize (Sync)
  2. Remove possible Imports from kotlinx.android.synthetic in the project
  3. In the build.gradle, inside the keys of buildFeatures add the following line:

viewBinding = true

  1. In the onCreate() method, make the viewBinding statement by calling the inflate method, example:
private lateinit var binding: ResultProfileBinding
 
override fun onCreate(savedInstanceState: Bundle?) {
   super.onCreate(savedInstanceState)
   binding = ResultProfileBinding.inflate(layoutInflater)
   val view = binding.root
   setContentView(view) 
}

Now you can use viewBinding to call the views

binding.name.text = viewModel.name
binding.button.setOnClickListener { viewModel.userClicked() }

doc: Kotlin Extensions Deprecated

0

API 28, A apply plugin: 'Kotlin-android-Extensions' is already inserted in Glade by default.

I just needed the import kotlinx.android.synthetic.main.activity_main.*

fun actionButton(view: View){
    val text = "O texto escolhido: "
    textSelection.text = text
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.