我在我的佈局中添加一個RadioButton。單選按鈕不會切換其狀態
這是沒有檢查開始。當我點擊它時,它會被檢查(如模擬器所示)。但是當我再次點擊它時,它不會再被取消選中?
<RadioButton android:checked="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/option1"/>
我在我的佈局中添加一個RadioButton。單選按鈕不會切換其狀態
這是沒有檢查開始。當我點擊它時,它會被檢查(如模擬器所示)。但是當我再次點擊它時,它不會再被取消選中?
<RadioButton android:checked="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/option1"/>
如果您只使用一個收音機盒進行檢查和關閉,也許應該使用複選框或切換按鈕。
http://developer.android.com/resources/tutorials/views/hello-formstuff.html
向下滾動,看到複選框和切換按鈕。
使用無線電時,通常有多個無線電,並在它們之間進行選擇。像簡單,中等,很難。
我該如何在自己的控件中指定'android's checkboxStyle'? – michael 2010-07-26 21:42:44
這是一個概念性問題:單選按鈕允許您在多個選項(由其他單選按鈕表示)之間進行選擇。通常,組中的一個單選按鈕始終被檢查,即使在初始狀態下,如果您沒有聲明一個按鈕爲默認值,也不會檢查任何按鈕。這意味着一個按鈕不允許切換其狀態,除非其他單選按鈕出現在同一組中 - 如果只有一個選項,則必須選擇它。
如果您想要二進制切換,您將希望使用複選框。
如果你有超過1個單選按鈕與再添加如下「RadioGroups」的工作:
<RadioGroup android:id="@+id/group1" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="vertical">
<RadioButton android:id="@+id/radio1" android:text="madras"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
<RadioButton android:id="@+id/radio2" android:text="bombay"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RadioGroup>
看一看這個example,我相信這會令你的想法明確有關收音機按鈕。
的解決方案是設置檢查[真/假]如果你正在尋找一個單選按鈕的外觀複選框行爲中間Java代碼
ToggleButton t = (ToggleButton) findViewById(R.id.toggle_button);
t.setChecked(true);
// t.setChecked(false);
,你可以在XML風格傳遞給一個複選框。
<CheckBox android:checked="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/option1"
style="@android:style/Widget.DeviceDefault.Light.CompoundButton.RadioButton/>
這可以(用在RecyclerView單選按鈕前)。在某些情況下非常有用,但因爲用戶希望單選按鈕的行爲以一定的方式,你應該小心。如果您允許用戶進行多項選擇,則應該使用正常複選框,如上面的註釋中所述。
希望這有助於!
在搜索了很多關於SO後,我想出了一個不太好但體面的解決方法。
爲每個RadioButton聲明一個boolean
變量,用false
對其初始化,並在每次點擊時更改變量和RadioButton的狀態。
boolean isToggledRadio1 = false;
RadioButton radio1 = (RadioButton) findViewById(R.id.radiobutton1);
radio1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
isToggledRadio1 = !isToggledRadio1; //Switch boolean value
RadioButton rb = (RadioButton)v;
rb.setChecked(isToggledRadio1);
}
});
我知道這是理想的使用複選框,但如果有人需要的單選按鈕,然後他們需要的單選按鈕。
這不是一個最佳的解決方案,因爲它會在每次用戶點擊該按鈕時基本上切換按鈕兩次(一個是默認行爲,第二次就是你的onclick函數中),所以如果你」重新使用OnCheckedChangeListener
,您可能會收到兩次同樣的點擊。
還有另一種解決方法,即將複選框中的android:button
更改爲帶有xml模板的另一個drawable,但它稍微複雜一些,需要至少2個以上的文件才能存在。
它適用於我。謝謝 – Vrajesh 2018-03-05 09:24:53
但是,這是一個單選按鈕*應該*的工作方式。 – 2010-07-26 19:42:49