表示色の設定

広告

表示される文字列の文字色を設定する方法を確認します。「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クラス」を参照して下さい。

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

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.graphics.Color;

public class Test extends Activity {
    @Override protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        TextView tv = new TextView(this);
        tv.setText("Text");
        tv.setTextColor(Color.RED);
        setContentView(tv);
    }
}

サンプルプログラム

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

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.graphics.Color;

public class Test03_01 extends Activity
{
    private final int WRAP_CONTENT = 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 tv1 = new TextView(this);
        tv1.setText("Color Red");
        tv1.setTextColor(Color.RED);
        linearLayout.addView(tv1, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

        TextView tv2 = new TextView(this);
        tv2.setText("Color RGB[127, 127, 0]");
        tv2.setTextColor(Color.rgb(127, 127, 0));
        linearLayout.addView(tv2, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
    }
}

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

文字色の設定

文字の色が指定した色に設定されていることが確認できました。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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