LoginSignup
4
2

More than 5 years have passed since last update.

Androidアプリ制作で、strings.xmlに代入したい

Posted at

string.xmlとは

アプリ内で使う文字列を定義する。
別にファイル名はstringsである必要性は無い。何でもよい。
でも、変える方が分かりづらい。

例えば、

<resources>
    <string name="app_name">Application Name</string>
<resources>

としておく。すると、画面デザインのxmlで

<TextView  
    android:id="@+id/title"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:text="@string/app_name"  
    />  

みたいにしておけば全て同じApplication Nameが表示される。
一括での変更が楽。
もちろん、Java内でも使える。

String title = getString(R.string.app_name);

例えば、「ようこそ、〇〇さん!」の場合

流石に、

String title = getString(R.string.youkoso) + name + getString(R.string.san);

みたいなのは無しだというのはご理解いただけると思う。
「〇〇さん、ようこそ!」に変更したい、となった時に変更する箇所が多いし。

こういう場合は、strings.xml内に

<string name="message">ようこそ、%1$dさん!</string>

としておくと、後で代入することができる。
こんな感じに。

String str = getString(R.string.message, name);

更には、複数の場合も対応している。
%nの所で順番を示しているので、

<string name="message">あなたは%2$s人目のお客様です!ようこそ、%1$dさん!</string>

みたいに定義しておけば、

String str = getString(R.string.message, name, count);

という具合に使える。

4
2
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
4
2