Reputation: 444
I created a new Kotlin project in the latest version of Android Studio, using the empty activity project template, which only contains a TextView with "Hello, World!" in its main layout. Then:
viewBinding
in the module build.gradle
.binding
in MainActivity.kt
(as shown in the last listing).txt_hello
as follows:<?xml version="1.0" encoding="utf-8"?>
<...>
<TextView
android:id="@+id/txtHello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</...>
Then I went on to MainActivity.kt
file to define some code that modifies the text
attribute of the txt_hellow
TextView
widget as follows:
package com.example.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
// I added this:
import com.example.myapplication.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// I removed this:
// setContentView(R.layout.activity_main)
// I added this:
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.txtHello.setOnClickListener {
binding.txtHello.setText("lel")
}
}
}
But, I get the following error:
String literal in
setText
can not be translated. Use Android resources instead.
How can I update widgets using the viewBinding
approach?
Upvotes: 0
Views: 531
Reputation: 444
First I think that's a warning that you shouldn't use a hardcoded string in the text view, because it's a bad practice and cannot be translated.
So you have to create some string values in your strings.xml, for example:
<string name="text_hello">Hello</string>
And use that string value like this
binding.txtHello.text = getText(R.string.text_hello)
Upvotes: 2
Reputation: 93599
That error is because you can't use binding.txtHello.text = "lel"
The reason for this is that there are two definitions of setText- one for a string and one for an int (a text resource). This means the code that converts setters from Java to Kotlin doesn't know which to call when you try to assign to the text variable, so it throws this error. Instead, use binding.txtHell.setText("lel"). You need to do this whenever there are multiple functions named setXXX for a given XXX written in Java.
Upvotes: 1