这里用一个实例,介绍radio的基本使用 :一个radioGroup中的两个radio,点击相应的,在textView中显示相应文字
1 String.xml中显示
<string name="tr_radio_op1">大头娘娘</string>
<string name="tr_radio_op2">小头皇帝</string>
<string name="str_radio_question1">请问你是?</string>
2 布局中的使用
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="match_parent" android:orientation="vertical" > <!--第一個TextView --> <TextView android:id="@+id/myTextView" android:layout_width="228px" android:layout_height="49px" android:text="@string/str_radio_question1" android:textSize="30sp" /> <!--建立一個RadioGroup --> <RadioGroup android:id="@+id/myRadioGroup" android:layout_width="137px" android:layout_height="216px" android:orientation="vertical" > <!--第一個RadioButton --> <RadioButton android:id="@+id/myRadioButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tr_radio_op1" /> <!--第二個RadioButton --> <RadioButton android:id="@+id/myRadioButton2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tr_radio_op2" /> </RadioGroup> </LinearLayout>
3 java的例子
import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
/**
* RadioGroup 的学习
*/
public class RadioGroupActivity extends Activity {
public TextView mTextView1;
public RadioGroup mRadioGroup1;
public RadioButton mRadio1, mRadio2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.radiogroup);
/* 取得 TextView、RadioGroup、RadioButton对象 */
mTextView1 = (TextView) findViewById(R.id.myTextView);
mRadioGroup1 = (RadioGroup) findViewById(R.id.myRadioGroup);
mRadio1 = (RadioButton) findViewById(R.id.myRadioButton1);
mRadio2 = (RadioButton) findViewById(R.id.myRadioButton2);
/* RadioGroup用OnCheckedChangeListener来运行 */
mRadioGroup1.setOnCheckedChangeListener(mChangeRadio);
}
private RadioGroup.OnCheckedChangeListener mChangeRadio = new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == mRadio1.getId()) {
/* 把mRadio1的内容传到mTextView1 */
mTextView1.setText(mRadio1.getText());
} else if (checkedId == mRadio2.getId()) {
/* 把mRadio2的内容传到mTextView1 */
mTextView1.setText(mRadio2.getText());
}
}
};
}