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) } }
In the Project > Android panel on the left, select ModuleName > res > values. Double-click strings. xml to open it for editing.
String. xml file contains all the strings which will be used frequently in Android project. String. xml file present in the values folder which is sub folder of res folder in project structure.In Android Studio, we have many Views such as TextView,Button,EditText,CheckBox,RadioButton etc.
We can easily access the element of the string using string[index]. Elements store in a string from index 0 to (string. length – 1). Using index: Returns the character at specified index.
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(...)
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With