- Home ›
- Android入門 ›
- TextViewクラス ›
- HERE
背景色の設定
広告
背景色を設定する方法を確認します。「TextView」クラスの親クラスである「View」クラスで用意されている「setBackgroundColor」メソッドを使います。
setBackgroundColor public void setBackgroundColor(int color)
Sets the background color for this view. Parameters: color the color of the background
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.setBackgroundColor(Color.RED);
setContentView(tv);
}
}
サンプルプログラム
それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。
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 Test04_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.setBackgroundColor(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.setBackgroundColor(Color.rgb(127, 127, 0));
linearLayout.addView(tv2,
new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
}
}
ビルド後にエミュレーター上で実行します。
背景色が指定した色に設定されていることが確認できました。
( Written by Tatsuo Ikura )
JavaDrive