How to access values from strings.xml

前端 未结 4 839
再見小時候
再見小時候 2020-12-09 15:18

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

class MainActivity : AppCompatActivity(), View.OnClickListener {
    override fun onClick(p0: Vie         


        
相关标签:
4条回答
  • 2020-12-09 15:28

    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>
    
    0 讨论(0)
  • 2020-12-09 15:34

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

    0 讨论(0)
  • 2020-12-09 15:40

    If you need to access the entire array:

    val data= resources.getStringArray(R.array.array_id)
    
    0 讨论(0)
  • 2020-12-09 15:52

    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
    
    0 讨论(0)
提交回复
热议问题