- Home ›
- Android入門 ›
- EditTextクラス ›
- HERE
幅を設定
テキストボックスの幅を設定します。「EditText」クラスの親クラスである「TextView」クラスで用意されている「setWidth」メソッドを使います。
setWidth public void setWidth(int pixels)
Makes the TextView exactly this many pixels wide. You could do the same thing by specifying this number in the LayoutParams. Related XML Attributes: android:width Parameters: pixels 幅(単位ピクセル)
テキストボックスとして文字を入力可能なエリアの幅を設定します。単位はピクセルです。
具体的には次のように記述します。
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
public class Test extends Activity {
@Override protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
EditText edit = new EditText(this);
edit.setWidth(50);
setContentView(edit);
}
}
テキストボックスは指定の幅に設定されます。この場合、入りきらないほどの文字を入力した場合には自動的に行が拡張されて複数の行が入力できるようになります。詳しくは次のサンプルを見てください。
サンプルプログラム
それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。
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.EditText;
public class Test02_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 tv = new TextView(this);
tv.setText("What's your name?");
linearLayout.addView(tv,
new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
EditText edit1 = new EditText(this);
edit1.setWidth(50);
linearLayout.addView(edit1,
new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
EditText edit2 = new EditText(this);
edit2.setWidth(100);
linearLayout.addView(edit2,
new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
}
}
ビルド後にエミュレーター上で実行します。
キーボード又はエミュレーター上のキーボードから文字を入力して下さい。
文字を追加していくと、設定した幅に入りきらなくなります。この場合、テキストボックスは横に拡張されるのではなく自動的に縦方向に拡張されます。
( Written by Tatsuo Ikura )
JavaDrive