ラジオボタンの利用とラベルに文字を表示する (RadioGroupとTextViewコントロールの利用)
ラジオボタンを使用します。ラジオボタンを扱う場合には、RadioGroupとRadioButtonコントロールを使います。
実装例
プロジェクトの設定
Androidプロジェクトを新規作成します。
- Project name: SimpleRadioTextView
- Build Target: Android 2.1-update1
- Application name: Simple Radio TextView
- Package name: iPentec.SimpleRadioTextView
- Activity: SimpleRadioTextView
UI
main.xmlを開き画面をデザインします。左側の[Palette]からRadioGroupをドラッグ&ドロップします。
左側の[Palette]からTextViewコントロールをドラッグ&ドロップして配置します。
TextViewを選択して右クリックしてポップアップメニューを表示します。ポップアップメニューの[Layout Width]メニューの[Fill Parent]メニューをクリックします。
[Fill Parent]メニューをクリックすると、TextViewの幅が画面いっぱいになります。
次にTextViewの文字列を中央ぞろえにします。TextViewをクリックして右クリックでポップアップメニューを表示します。ポップアップメニューの[Properties]メニューの[Gravity]サブメニューの[Center]メニューをクリックします。
下図のように文字列がセンタリングされます。
コード
コードを記述します。
package iPentec.SimpleRadioTextView;
import android.app.Activity;
import android.os.Bundle;
import android.widget.*;
import android.view.View;
public class SimpleRadioTextView extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick_RadioButton(View view){
TextView textView1 = (TextView)findViewById(R.id.textView1);
RadioGroup radioGroup1 = (RadioGroup)findViewById(R.id.radioGroup1);
RadioButton radio = (RadioButton)findViewById(radioGroup1.getCheckedRadioButtonId());
textView1.setText(radio.getText());
}
}
実行結果
アプリケーションを実行します。
エミュレーターが起動し下図の画面が表示されます。
[Duck]ラジオボタンをクリックします。下のTextViewの文字列がDuckに変わります。
[Goose]ラジオボタンをクリックすると、下のTextViewの文字列がGooseに変わります。
参考
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<RadioGroup android:layout_height="wrap_content" android:id="@+id/radioGroup1" android:layout_width="fill_parent">
<RadioButton android:layout_width="wrap_content" android:id="@+id/radio0" android:layout_height="wrap_content" android:text="Penguin" android:checked="true" android:onClick="onClick_RadioButton"></RadioButton>
<RadioButton android:layout_width="wrap_content" android:id="@+id/radio1" android:layout_height="wrap_content" android:text="Duck" android:onClick="onClick_RadioButton"></RadioButton>
<RadioButton android:layout_width="wrap_content" android:id="@+id/radio2" android:layout_height="wrap_content" android:text="Goose" android:onClick="onClick_RadioButton"></RadioButton>
</RadioGroup>
<TextView android:id="@+id/textView1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="TextView" android:gravity="center"></TextView>
</LinearLayout>
著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。