How to dynamically update widget text using "latest" best Kotlin Android pratcices?

Issue

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:

  1. I enabled viewBinding in the module build.gradle.
  2. Defined binding in MainActivity.kt (as shown in the last listing).
  3. 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:

  1. How to update widgets using the viewBinding approach?

Solution

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)

Answered By – galihif

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published