- Home ›
- Android入門 ›
- CheckBoxクラス ›
- HERE
パディングの設定
広告
文字列を表示する時に表示エリアとの間にパディングを設定する方法を確認します。「Checkbox」クラスの親クラスである「TextView」クラスで用意されている「setPadding」メソッドを使います。
setPadding public void setPadding(int left, int top, int right, int bottom)
Sets the padding. Parameters: left the left padding in pixels top the top padding in pixels right the right padding in pixels bottom the bottom padding in pixels
4つの引数を使って左上右下の順にパディングの量を設定します。単位はピクセルです。
チェックボックスでは文字列の他に、現在チェックされているかどうかを表す画像が左側に表示されています。デフォルトで画像の右側に文字列が表示されるように、左側にはある程度のパディングが設定されています。パディングを設定する場合にはその点に注意して下さい。
具体的には次のように記述します。
@Override protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
CheckBox checkbox = new CheckBox(this);
checkbox.setText("checkbox");
checkbox.setPadding(5, 5, 5, 5);
setContentView(checkbox);
}
サンプルプログラム
それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。
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 Test05_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.setBackgroundColor(Color.RED);
linearLayout.addView(checkbox1, createParam(WC, WC));
CheckBox checkbox2 = new CheckBox(this);
checkbox2.setText("Coffee");
checkbox2.setBackgroundColor(Color.GREEN);
checkbox2.setPadding(5, 5, 5, 5);
linearLayout.addView(checkbox2, createParam(WC, WC));
CheckBox checkbox3 = new CheckBox(this);
checkbox3.setText("Potato");
checkbox3.setBackgroundColor(Color.YELLOW);
checkbox3.setPadding(30, 5, 5, 5);
linearLayout.addView(checkbox3, createParam(WC, WC));
}
private LinearLayout.LayoutParams createParam(int w, int h){
return new LinearLayout.LayoutParams(w, h);
}
}
ビルド後にエミュレーター上で実行します。
左側に適切なパディングが設定されていないと、文字列と状態表示用の画像が重なってしまいますので注意して下さい。
( Written by Tatsuo Ikura )
JavaDrive