How to access values from strings.xml
AndroidKotlinAndroid Problem Overview
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)
}
}
Android Solutions
Solution 1 - Android
Accessing string values in Kotlin works exactly the same as it does in Java, just with Kotlin syntax:
val string: String = getString(R.string.your_string_id)
(This assumes that your code is inside an Android Activity
, or a similar class that inherits from Context
. If not, you need to get a Context
instance from somewhere, and change it to myContext.getString(...)
.)
Solution 2 - Android
if you're accessing it outside oncreate then
Resources.getSystem().getString(R.string.btn_yes)
Solution 3 - Android
If you need to access the entire array:
val data= resources.getStringArray(R.array.array_id)
Solution 4 - Android
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
Solution 5 - Android
To use strings.xml in my code I do the following:
textView.text = "${getString(R.string.my_text)}"
Solution 6 - Android
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>
Solution 7 - Android
I used it for titlebar, but my app crashed.
private var title: String = getString(R.string.profile)
Solution 8 - Android
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"