文字色の設定

広告

チェックボックスに表示される文字の色を設定します。「Checkbox」クラスの親クラスである「TextView」クラスで用意されている「setTextColor」メソッドを使います。

Set the text color for all the states (normal, selected, focused) to be 
this color.

Related XML Attributes:
  android:textColor
Parameters:
  color  文字色

1番目の引数に文字色を指定します。色の指定には「android.graphics.Color」クラスを使います。詳しくは「Colorクラス」を参照して下さい。

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

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

    CheckBox checkbox = new CheckBox(this);
    checkbox.setText("checkbox");
    checkbox.setTextColor(Color.RED);
    setContentView(checkbox);
}

サンプルプログラム

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

Test03_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.widget.CheckBox;
import android.graphics.Color;

public class Test03_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);

        TextView text = new TextView(this);
        text.setText("What would you like to have?");
        linearLayout.addView(text, createParam(WC, WC));

        CheckBox checkbox1 = new CheckBox(this);
        checkbox1.setText("Hamburger");
        checkbox1.setTextColor(Color.RED);
        linearLayout.addView(checkbox1, createParam(WC, WC));

        CheckBox checkbox2 = new CheckBox(this);
        checkbox2.setText("Coffee");
        checkbox2.setTextColor(Color.GREEN);
        linearLayout.addView(checkbox2, createParam(WC, WC));
    }

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

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

文字色の設定

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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