0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Androidでリソースを取得する

0
Posted at

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であり、実際の文字列へ変換するにはContextResourcesが必要です。そのためobjectなどContextを持たないクラスでは、呼び出し元からContextを受け取って文字列を取得します。

レイアウト

レイアウトXMLでは、@string/を使用します。

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/app_name" />
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?