色リソースの取得

広告

リソースIDを指定して色のリソースを取得する方法を確認します。「Resources」クラスで用意されている「getColor」メソッドを使います。

Return a color integer associated with a particular resource ID. 
Throws NotFoundException if the given ID does not exist.

Parameters:
id  The desired resource identifier, as generated by the aapt tool. This 
  integer encodes the package, type, and resource entry. The value 0 is an 
  invalid identifier.

Returns:
  int A color value in the form 0xAARRGGBB.

1番目の引数には色リソースに対して「R.java」ファイル内で割り当てられた値を指定します。戻り値としてリソースIDに対応した色リソースを使った色を表すint型の値を取得できます。

※色のリソースは文字列として定義しますが、文字列から色を表すint型の値に自動的に変換し返します。色のリソースの登録方法については「文字列や色のリソース定義」を参照して下さい。また色そのものについては「Colorクラス」を参照して下さい。

具体的には次のように記述します。

@Override protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    Resources res = getResources();
    int color = res.getColor(R.color.olive);
}

サンプルプログラム

それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。

Test02_01.java

package jp.javadrive.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.view.ViewGroup;
import android.widget.TextView;
import android.content.Resources;

public class Test02_01 extends Activity {
    private final int FP = ViewGroup.LayoutParams.FILL_PARENT; 
    private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT; 

    @Override protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        setContentView(linearLayout);

        Resources res = getResources();
        int olive_color = res.getColor(R.color.olive);
        int chocolate_color = res.getColor(R.color.chocolate);

        TextView text1 = new TextView(this);
        text1.setText("Olive Color");
        text1.setBackgroundColor(olive_color);
        linearLayout.addView(text1, createParam(WC, WC));

        TextView text2 = new TextView(this);
        text2.setText("Chocolate Color");
        text2.setBackgroundColor(chocolate_color);
        linearLayout.addView(text2, createParam(WC, WC));
    }

    private LinearLayout.LayoutParams createParam(int w, int h){
        return new LinearLayout.LayoutParams(w, h);
    }
}

またプロジェクト内の「res/values」ディレクトリ内に「color.xml」ファイルを作成し次のように色リソースを定義しました。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="olive">#808000</color>
    <color name="chocolate">#d2691e</color>
</resources>

ビルド後にエミュレーター上で実行します。

色リソースの取得

色リソースとして定義した色をプログラム中で参照し利用できていることが確認できました。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。