こんばんはざっきーです。
今回もボタンシリーズです。
今回はラジオボタンをやってみます。
ラジオボタンというのは、ひとつのグループの中で一つのボタンだけ選択するときに使われます。
ラジオボタンのコンポーネントには
1、ひとつを選択すると、他のボタンの選択が取り消される。
2、クリックされたボタンを取得する事ができる。
という動作が、デフォルトで含まれています。
今回のプロジェクト、クラス名はrButtonにしました。(安直すぎわろりん
いつものようにmain.xmlの【graphical layout】でレイアウトを行います。
今回はradionGroupをドラッグして入れます。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<requestFocus />
<RadioGroup
android:layout_height="wrap_content"
android:id="@+id/radioGroup1"
android:layout_width="fill_parent">
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton"
android:checked="true"></RadioButton>
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton"></RadioButton>
<RadioButton
android:id="@+id/radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton"></RadioButton>
</RadioGroup>
</LinearLayout>
これでラジオボタンの配置はできました。
この状態で実行すると

こんな感じになります。
ここで例えば3を選ぶと、3番が選択され1番の選択が解除されます。
radionGroupに
android:orientation="horizontal"
を追加すると、項目が横に並びます。
水平(horizontal)と垂直(vertical)で縦、横の並びに切り替えれます。
次はこの配置したレイアウトをスクリプトで利用してみます。
package zacky.android.rbutton;
import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
public class RButton extends Activity implements OnCheckedChangeListener{
/** Called when the activity is first created. */
private RadioGroup radioGroup;
private TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
radioGroup = (RadioGroup)findViewById(R.id.radioGroup1);
textView = (TextView)findViewById(R.id.textView1);
radioGroup.setOnCheckedChangeListener(this);
}
public void onCheckedChanged(RadioGroup arg0,int arg1){
if(arg0 == radioGroup){
switch(arg1){
case R.id.radioButton1:
textView.setText("1つめをクリックしたな!");
break;
case R.id.radioButton2:
textView.setText("2つめをクリックしたな?");
break;
case R.id.radioButton3:
textView.setText("3つめをクリックしたのね・・・");
break;
default:
break;
}
}
}
}
これでラジオボタンを押す度に値が対応したものに切り替わります。
今回はわかりやすいようにTextViewの中に入れて利用しましたが
実際には内部の値を変更して使う事になるんじゃないかと思います。
今回はこれでおしまいです。
お疲れ様でした。