2010-10-27 45 views
22

如果我第一次設置了單選按鈕,它將正常工作。但是,如果我通過調用 ((RadioButton)findViewById(R.id.ID))來取消選擇。setChecked(false); 然後,即使我嘗試通過調用setChecked(true)來使其選中,除非用戶從屏幕中選擇它,否則將不起作用。Android RadioButton無法使用setChecked(false)方法取消設置

有沒有人遇到過這個?還是隻有我?

 if(Val != null){ 
     if(((RadioButton) findViewById(R.id.ID1)).getText().toString().trim().equals(Val)) 
     ((RadioButton) findViewById(R.id.ID1)).setChecked(true); 
     else if(((RadioButton) findViewById(R.id.ID2)).getText().toString().trim().equals(Val)) 
     ((RadioButton) findViewById(R.id.ID2)).setChecked(true); 
     } 
     else { 
      ((RadioButton) findViewById(R.id.ID1)).setChecked(false); 
      ((RadioButton) findViewById(R.id.ID2)).setChecked(false); 
     } 

如果else部分被執行至少一次,那麼所有東西都會變得混亂起來。 當我跳過調試器時,我可以看到執行進入正確的路徑並將其設置爲true。它只被執行一次,我檢查了這一點。而且我不會將代碼的任何其他部分重置爲false。

+0

我們能否看到您的源代碼? – ykatchou 2010-10-27 16:34:24

+0

我試過這個android:saveEnabled =「false」,在去http://groups.google.com/group/android-developers/browse_thread/thread/8ad42efded222543之後,但是這並沒有幫助我。哇至少我是不是一個人...... – franklins 2010-10-27 16:44:11

+1

有同樣的問題,雖然我的佈局 圖片 - 文本 - 檢查 圖片 - 文本 - 檢查 我不能讓只有一個RadioGroup中...我發現它是一個'錯誤',當我不能用setChecked(false)設置Radio時,android-developer必須做什麼unfix。 感謝您的信息,將嘗試... – 2011-01-25 19:50:11

回答

48

我找到了解決方案。

不可能取消選中某個單選按鈕。您只能將其他項目設置爲true。

因此,要清除所有選中的項目,您應該在RadioGroup上調用clearcheck()方法。

所以我的其他部分是

 else { 
      ((RadioGroup) findViewById(R.id.ID0)).clearCheck(); 
     } 
+0

正是我需要的!有時候單選按鈕會變得非常麻煩。謝謝! – 2015-04-27 19:01:59

+0

或者在我的情況下,當我脫掉RadioGroup並使用兩個RadioButton玩時,它就變得更加清晰。 – samutamm 2016-06-01 08:02:21

+0

這解決了我的問題。我試圖重新檢查已經檢查過的單選按鈕,它在UI中沒有選中它。 – W00di 2016-11-24 03:52:48

2

取一個無形的單選按鈕,並檢查它。組的所有其他單選按鈕將被自動取消選中。