AndroidTips | styles.xmlにについて
Androidプロジェクト内のresフォルダに、valuesフォルダがあります。
このフォルダ内にはstrings.xml、styles.xmlなどが配置されています。
このstyles.xmlは名前の通りAndroidのスタイルを定義する際に使用します。
以下のコードを確認してください。
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Light">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
<!-- 1つめのTextViewのスタイルを定義 -->
<style name="text1">
<item name="android:textStyle">italic</item>
<item name="android:textColor">#9400D3</item>
</style>
<!-- 2つめのTextViewのスタイルを定義 -->
<style name="text2">
<item name="android:textSize">18sp</item>
<item name="android:textColor">#32CD32</item>
</style>
</resources>
21行目から24行目で<style>を用いて、「text1」という名前のスタイルを定義しています。
そしてこの中では<item>を用いて、フォントをカラーを指定しています。
また、27行目から30行目で<style>を用いて、「text2」という名前のスタイルを定義しています。
そしてこの中では<item>を用いて、文字の大きさとカラーを指定しています。
この他にも<item>で、name属性の値に指定できるものはたくさんあります。
どのようなものがあるのか調べてみると良いと思います。(あまりにも量が多いので今回は割愛します。)
次にそのスタイルを適用したいview側の処理です。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
style="@style/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<TextView
style="@style/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<TextView
style="@style/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</LinearLayout>
上記のようにstyle属性を用いて、その値に先ほど作成したスタイル名を指定すればOKです。
例えば、10行目では「styleファイルのtext1」を指定しています。
このアプリの実行画面は以下のようになります。
[styled_images width=”168px” height=”280px”]
[image title=”1″ ]https://techpjin.sakura.ne.jp/techpjin_new/wp-content/uploads/2014/03/device-2014-03-03-153456.png[/image]
[/styled_images]
[clearboth]
さて、このように別ファイルで定義する理由として、strings.xmlの際と同じで、当然次の2つが挙げられます。
- 画面レイアウトファイルのコードが簡潔になり、メンテナンス性が上がる
- スタイルを一つ定義して、複数のviewに設定することが可能
(今回の例では1つめのTextViewと2つ目のTextViewに同じスタイルを適応しています。)
以上を踏まえた上で上手に活用しましょう。本日はここまでとします。