要使用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' –