how can i access values from strings.xml in kotlin

2019-06-16 05:51发布

问题:

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)
    }
}

回答1:

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)


回答2:

If you need to access the entire array:

val data= resources.getStringArray(R.array.array_id)


回答3:

If you wanted to access String out of a context or Activity (e.g Data Model Class) you can achieve like this:

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

EDIT: It's only for system-wide resources, not Application resources