表示文字列の設定
広告
ボタンに表示される文字列を設定します。「Button」クラスの親クラスである「TextView」クラスで用意されている「setText」メソッドを使います。
setText public final void setText(CharSequence text)
Sets the text that this TextView is to display (see setText(CharSequence)) Related XML Attributes: android:text Parameters: text 表示文字列
1番目の引数には表示する文字列を指定します。
具体的には次のように記述します。
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
public class Test extends Activity {
@Override protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
Button button = new Button(this);
button.setText("button");
setContentView(button);
}
}
サンプルプログラム
それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。
package jp.javadrive.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.view.ViewGroup;
import android.widget.Button;
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);
Button button1 = new Button(this);
button1.setText("Yes");
linearLayout.addView(button1,
new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
Button button2 = new Button(this);
button2.setText("No");
linearLayout.addView(button2,
new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
}
}
ビルド後にエミュレーター上で実行します。
指定した文字列が表示されました。
( Written by Tatsuo Ikura )
JavaDrive