<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="test1" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="test2" />
</RadioGroup>
Source Code
package com.radio;
//與CheckBox差在RadioButton常用於單選選項
import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
public class Radio2Activity extends Activity {
/** Called when the activity is first created. */
RadioGroup rg;
RadioButton rb1, rb2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rg = (RadioGroup) findViewById(R.id.radioGroup1);
rb1 = (RadioButton) findViewById(R.id.radio0);
rb2 = (RadioButton) findViewById(R.id.radio1);
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
/*
* arg1本身為整數型別,此整數代表原件於R.java之編號,
* 因此可以用於判斷使用者按下哪個RadioButton,以getId()方法
*/
public void onCheckedChanged(RadioGroup arg0, int arg1) {
// TODO Auto-generated method stub
if (arg1 == rb1.getId()) {
Toast.makeText(Radio2Activity.this, "test1", 3000).show();
} else if (arg1 == rb2.getId()) {
Toast.makeText(Radio2Activity.this, "test2", 3000).show();
}
}
});
}
}
沒有留言:
張貼留言