コンピュータクワガタ

かっぱのかっぱによるコンピュータ関連のサイトです

Androidアプリ入門 No.02 色の定義

ウィジェット共通

今回からウィジェット共通の要素について解説する。最初は色の定義を確認する。

ここでは色の指定方法を確認する。前回ののmain.xmlを以下のように変更する。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:id="@+id/textView1"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    android:textColor="#000"
    android:background="#ffffff"
    />
</LinearLayout>

この状態でプログラムを実行すると以下のようになる。

色の指定は、ドキュメントにあるとおり以下のいずれかの形式で指定できる。

  • #RGB
  • #ARGB
  • #RRGGBB
  • #AARRGGBB

A、R、G、Bすべて0〜Fの16進数で定義する。Aは透明度を示し0は透明でFは不透明を表す。RGBはそれぞれ赤、緑、青と対応する。上記の例ではTextViewの背景色を白、文字の色を黒にしている。
次に透明度のテストをする。main.xmlを以下のように変更する。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/blue"
    >
<TextView
    android:id="@+id/textView1"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    android:textColor="#000"
    android:background="#80ffffff"
    />
</LinearLayout>

また、strings.xmlを以下のようにする。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">ActivityTest</string>

    <color name="blue">#0000ff</color>
</resources>

実行結果は以下のようになる。メインのレイアウトを青にし、TextViewの背景色を白の半透明にしたため、TextViewの背景が水色になっている。

また、色の指定でリソースを指定している。最初に行ったものと違い色のリソースは「@color/リソースの名称」で定義する。今回は、青色のためblueとした。具体的な色の定義はresource.xmlにcolor要素として定義する。指定する値としては通常のリテラルの定義と同様である。同じリソースの指定でも文字列はstring、色はcolorと用途に応じて違う属性値を指定するのが非常にわかりやすい。