如何从strings.xml访问值 [英] How to access values from strings.xml

查看:67
本文介绍了如何从strings.xml访问值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从Kotlin android中的strings.xml中访问值?

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

推荐答案

使用Kotlin语法,在Kotlin中访问字符串值的工作原理与在Java中完全相同:

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)

(这假设您的代码在Android Activity中,或者是从Context继承的类似类.如果没有,则需要从某个地方获取Context实例,并将其更改为myContext.getString(...) )

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

这篇关于如何从strings.xml访问值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆