Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access values from strings.xml

Tags:

android

kotlin

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)     } } 
like image 826
Dheeraj Avatar asked Jul 02 '17 13:07

Dheeraj


People also ask

How do I open a string in xml?

In the Project > Android panel on the left, select ModuleName > res > values. Double-click strings. xml to open it for editing.

Where can I find strings in xml?

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.

How do you access string in Kotlin?

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.


1 Answers

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(...).)

like image 90
Robin Avatar answered Sep 20 '22 23:09

Robin