Android:string.xmlの初歩的な使い方
現在TexhInstituteアプリ開発養成講座テキストを使って勉強しています。
テキストは2014年のものなので現在のバージョンと異なる事が多々あります。テキストのままやっても解決できなかった事や、テキストだけでは分からなかった事をここに書きます。
chapter7:7-1-3
string.xmlにて文字を打つ場所
「ScrollViewを使えば文字が沢山あってもスクロールして読める」という章で、
文字を書く際にテキストビューの中に埋め込まず、String.xmlを使う方法がいきなり紹介されました。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">SpinnerXml</string>
<string name="hello_world">Hello world!</string><!-- ここにとにかくたくさん の文字を書く -->
<string name="action_settings">Settings</string>
</resources>
しかし、上記の通り「ここに」沢山文字を打ったのですが般若心経ではなくHello World!が出力されました。(以下コード)
<?xml version="1.0" encoding="utf-8"?>
//この位置は失敗
<resources>
<string name="app_name">SpinnerXml</string>
<string name="hello_world">Hello world!</string>觀自在菩(中略)是大明呪是無
<string name="action_settings">Settings</string>
</resources>
勿論、文字を打つ場所は<string>の間でした。
//この位置が正解
<string name="hello_world">觀自在菩(中略)是大明呪是無</string>
全然「ここ」じゃないじゃん!
string.xmlの初歩的な使い方
例えば、TextViewを使って長文を表示させたい時、activity_main.xmlやfragment_main.xmlにそのまま書いてしまうと、XML内の構造(パーツは何があるか)がわかりにくくなるという問題が起こるのだと思います。または、その文章を別の部分で使いたい等もあるのかもしれません。
そんな時に、数文字の「変数」で表して別の場所に格納できたら見やすい(使いやすい)んじゃないか、ということでString.xmlが生まれたのだと思いました。
使い方は以下の通り。
TextViewのandroid:text="の後に文章をかくべきですが"
"@string/moji"を入れることで、
string.xmlの <string name="moji">に記載されてる文字を読み取ります。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
(後略)
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:text="@string/moji" />
<resources>
<string name="moji">Hello happy world!</string>
</resources>
<resources>
<string name="moji">Hello happy world!</string>
</resources>
string.xmlにはHello happy world!と記載されてるので、実行結果もそのようになります。
string.xmlの初歩的な使い方については以上です。
今回でいうmojiやHello happy worldを書き換えていろいろ遊んでみてください!
Author And Source
この問題について(Android:string.xmlの初歩的な使い方), 我々は、より多くの情報をここで見つけました https://qiita.com/RyukiBot/items/26b7f175fc3aa5daf5c6著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .