I created a new Kotlin project in latest Android studio, using the empty activity project template, which only contains a TextView with "Hello world!" in its main layout. Then:
- I enabled
viewBinding
in the modulebuild.gradle
. - Defined
binding
inMainActivity.kt
(as shown in the last listing). - Gave that TextView an identifier
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 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.
Which brings me to my question:
- How to update widgets using the
viewBinding
approach?
CodePudding user response:
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.
CodePudding user response:
First I think that's a warning that you shouldn't use a hardcoded string to 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)