Danilo Barreto
Posted on September 10, 2021
Hoje eu quero falar de uma forma melhor de referenciar controles dentro do Android com Kotlin sem ser usando o findViewById. Uma boa alternativa é usando o Viewbinding. Com ele temos, inclusive, o suporte do intelissense do Android Studio para localizar os nossos controles localizados no layouts.xml. Vamos ver como fazer?
Antes de mais nada coloque dentro do build.gradle da app o seguinte trecho:
buildFeatures{
viewBinding = true
}
Este trecho vai dentro do bloco android.
Agora dentro de MainActivity.kt você declara uma variável da seguinte forma:
lateinit var binding: ActivityMainBinding
Depois, dentro de onCreate inclua a seguinte instrução:
binding = ActivityMainBinding.inflate(layoutInflater)
Agora pra acessar o objeto declarado no xml tudo que é preciso é usar dessa forma:
binding.myTextView.text = "new text"
Layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="¿Hola?"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt
package com.avanade.viewbinding
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import com.avanade.viewbinding.databinding.ActivityMainBinding
import org.w3c.dom.Text
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(R.layout.activity_main)
//Antes
val oldButton: Button = findViewById<Button>(R.id.myButton)
val myText: TextView = findViewById<TextView>(R.id.myTextView)
//Agora
val button: Button = binding.myButton
val text: TextView = binding.myTextView
binding.myTextView.text = "new text"
}
}
Até a próxima!
Posted on September 10, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 21, 2024