- Home ›
 - Android入門 ›
 - RadioButtonクラス ›
 - HERE
 
表示文字列の設定
広告
ラジオボタンに表示される文字列を設定します。「RadioButton」クラスの親クラスである「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.RadioButton;
public class Test extends Activity {
    @Override protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        RadioButton radio = new RadioButton(this);
        radio.setText("radiobutton");
        setContentView(radio);
    }
}
					サンプルプログラム
それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。
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.RadioButton;
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("Which would you like to have?");
        linearLayout.addView(tv, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
        RadioButton radio1 = new RadioButton(this);
        radio1.setText("Hamburger");
        linearLayout.addView(radio1, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
        RadioButton radio2 = new RadioButton(this);
        radio2.setText("Pizza");
        linearLayout.addView(radio2, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
    }
}
					ビルド後にエミュレーター上で実行します。
					
					
					
					
指定した文字列がラジオボタンに表示されました。現時点でラジオボタンをグループ化していないため、チェックボックスと同じくどちらのラジオボタンにもチェックを行うことができます。
( Written by Tatsuo Ikura )
				
JavaDrive