- Home ›
 - Android入門 ›
 - TextViewクラス ›
 - HERE
 
パディングの設定
広告
文字列を表示する時に表示エリアとの間にパディングを設定する方法を確認します。「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つの引数を使って左上右下の順にパディングの量を設定します。単位はピクセルです。
具体的には次のように記述します。
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Test extends Activity {
    @Override protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        TextView tv = new TextView(this);
        tv.setText("Text");
        tv.setPadding(5, 5, 5, 5);
        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 Test09_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("Android");
        tv1.setBackgroundColor(Color.RED);
        linearLayout.addView(tv1, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
        TextView tv2 = new TextView(this);
        tv2.setText("Android");
        tv2.setBackgroundColor(Color.GREEN);
        tv2.setPadding(5, 5, 5, 5);
        linearLayout.addView(tv2, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
    }
}
					ビルド後にエミュレーター上で実行します。
					
					
2番目のビューでは上下左右に5ピクセルずつのパディングが設定されています。
( Written by Tatsuo Ikura )
				
JavaDrive