This content originally appeared on DEV Community and was authored by Danilo Barreto
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!
This content originally appeared on DEV Community and was authored by Danilo Barreto
Danilo Barreto | Sciencx (2021-09-10T13:53:38+00:00) Viewbinding. Retrieved from https://www.scien.cx/2021/09/10/viewbinding/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.