Androidでは、strings.xmlに定義した文字列を取得する方法が、クラスの種類によって異なります。よく使う取得方法をまとめます。
Activity、Fragment
ActivityとFragmentではgetString()がそのまま使用できます。
val text = getString(R.string.app_name)
object(シングルトン)
objectにはContextが存在しないので、呼び出し元から渡します。
object CommonUtil {
fun getMessage(context: Context): String {
return context.getString(R.string.app_name)
}
}
呼び出し側
CommonUtil.getMessage(requireContext())
Resourcesを利用する
Resourcesを保持している場合は、getString()で取得できます。
val text = resources.getString(R.string.app_name)
Application
Applicationから取得することもできます。
val text = application.getString(R.string.app_name)
R.string.app_nameは文字列リソースのIDであり、実際の文字列へ変換するにはContextやResourcesが必要です。そのためobjectなどContextを持たないクラスでは、呼び出し元からContextを受け取って文字列を取得します。
レイアウト
レイアウトXMLでは、@string/を使用します。
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name" />