背景色の設定

広告

背景色を設定する方法を確認します。「EditText」クラスの親クラスである「View」クラスで用意されている「setBackgroundColor」メソッドを使います。

Sets the background color for this view.

Parameters:
  color  the color of the background

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

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

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

    EditText edit = new EditText(this);
    edit.setText("", BufferType.NORMAL);
    edit.setBackgroundColor(Color.RED);
    setContentView(edit);
}

サンプルプログラム

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

Test09_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.EditText;
import android.widget.TextView.BufferType;
import android.graphics.Color;

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

        EditText edit1 = new EditText(this);
        edit1.setWidth(200);
        edit1.setText("Yamada", BufferType.NORMAL);
        edit1.setBackgroundColor(Color.RED);
        linearLayout.addView(edit1, createParam(WC, WC));

        EditText edit2 = new EditText(this);
        edit2.setWidth(200);
        edit2.setText("Katou", BufferType.NORMAL);
        edit2.setTextColor(Color.WHITE);
        edit2.setBackgroundColor(Color.rgb(127, 127, 0));
        linearLayout.addView(edit2, createParam(WC, WC));
    }

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

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

背景色の設定

背景色の設定

2つのテキストボックスが表示され、それぞれのテキストボックスの背景色が設定された色になっています。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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