How to access values from strings.xml

Viewed 88667

How can I access values from strings.xml in kotlin android?

class MainActivity : AppCompatActivity(), View.OnClickListener {
    override fun onClick(p0: View?) {
        getToastCalled("")
        TODO("not implemented")
    }

    private fun getToastCalled(message: String) {
        TODO("not implemented")
    }

    var btn: Button? = null;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var tv_name=findViewById(R.id.tv) as TextView
        btn=findViewById(R.id.button) as Button
        tv_name.setText(KtTest().name);
        (btn as Button).setOnClickListener(MainActivity@this)
    }
}
8 Answers

if you're accessing it outside oncreate then

    Resources.getSystem().getString(R.string.btn_yes)  

If it helps this is how I did it - you need the application context and also to import the R Class

applicationContext.getString(R.string.text_string)
import com.example.yourpackagename.R

To use strings.xml in my code I do the following:
textView.text = "${getString(R.string.my_text)}"

Use the format - R.string.string_name

Reference it explicitly for example:

R.string.loadingText,

Given your XML file has the following as part of the resources:

<string name="loadingText">The actual text to be displayed</string>

I used it for titlebar, but my app crashed.

private var title: String = getString(R.string.profile)

You can access string values simply through - "@string/variable_name".

For instance - if strings.xml contains entry like <string name="app_name">Tip Time</string>, then you can access it using -

"@string/app_name"
Related