要使用RadioButton
正常,你最好组一帮RadioButton
s转换为一组,命名为RadioGroup
。
<RadioGroup
android:id="@+id/rg1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RadioButton
android:id="@+id/rg1_rb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="North" />
<RadioButton
android:id="@+id/rg1_rb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="South" />
<RadioButton
android:id="@+id/rg1_rb3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Whatever" />
</RadioGroup>
关键的是,你必须设置独特android:id
每个RadioButton
S,否则将无法正常工作!
接下来,从您的XML中找到RadioButton
。
RadioButton rb1, rb2, rb3;
rb1 = (RadioButton) findViewById(R.id.rg1_rb1);
rb2 = (RadioButton) findViewById(R.id.rg1_rb2);
rb3 = (RadioButton) findViewById(R.id.rg1_rb3);
最后,准备RadioButton.OnClickListener
类实例并将其连接到RadioButton
秒。
View.OnClickListener optionOnClickListener
= new View.OnClickListener() {
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.textview);
String str = null;
// you can simply copy the string of clicked button.
str = ((RadioButton)v).getText().toString();
tv.setText(str);
// to go further with check state you can manually check each radiobutton and find which one is checked.
if(rb1.isChecked()) {
// do something
}
if(rb2.isChecked()) {
// do something
}
if(rb3.isChecked()) {
// do something
}
}
};
rb1.setOnClickListener(optionOnClickListener);
rb2.setOnClickListener(optionOnClickListener);
rb3.setOnClickListener(optionOnClickListener);
// check rb1 by default, if you want.
rb1.setChecked(true);
新增:
我很抱歉,但我不明白我的答案编辑的版本,因为调用setOnClickListener()的View.OnClickLister.OnClick内()对我来说有些奇怪。
所以我回到我原来的答案。
也显示您的XML。请记住将您的XML中的'onClick'侦听器设置为'onRadioButtonClicked' –