2012-03-11 32 views
1

我的單選按鈕可以正常工作,但選擇的第二個按鈕會變得粘滯。其他人可以選擇,他們切換,但顯示屏顯示第二個按鈕卡住。Android中的粘貼單選按鈕

請參閱下面的自包含代碼示例。我正在使用4.0.3並在使用eclipse的模擬器中運行。

感謝

package small.example; 
import android.app.Activity; 
import android.os.Bundle; 
import android.widget.*; 
public class SmallActivity extends Activity { 
    @Override public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     LinearLayout main=new LinearLayout(this); 
     main.setOrientation(LinearLayout.VERTICAL); 
     int question=1; 
     button=new Button(this); 
     button.setText("Make a choice"); 
     main.addView(button); 
     button.setId(question); 
     setContentView(main); 
     int answers=4; 
     radioButtons=new RadioButton[answers]; 
     RadioGroup radioGroup=addRadioButtonsToGroup(question,radioButtons); 
     LinearLayout linearLayout=new LinearLayout(this); 
     linearLayout.addView(radioGroup); 
     linearLayout.setId(question); 
     // radioButtons[0].setChecked(true); 
     main.addView(linearLayout); 
    } 
    private RadioGroup addRadioButtonsToGroup(int question,RadioButton[] radioButtons) { 
     RadioGroup radioGroup=new RadioGroup(this); 
     for(int i=0;i<radioButtons.length;i++) { 
      radioButtons[i]=new RadioButton(this); 
      radioButtons[i].setText("Question "+question+" Choice "+(i+1)); 
      radioButtons[i].setId(i); 
      radioGroup.addView(radioButtons[i]); 
     } 
     radioGroup.setOnCheckedChangeListener(radioGroupOnCheckedChangeListener); 
     radioGroup.setId(question); 
     return radioGroup; 
    } 
    RadioButton[] radioButtons; 
    Button button; 
    RadioGroup.OnCheckedChangeListener radioGroupOnCheckedChangeListener=new RadioGroup.OnCheckedChangeListener(){ 
     public void onCheckedChanged(RadioGroup group,int checkedId) { 
      int id=checkedId; 
      button.setText(radioButtons[id].getText()); 
     } 
    }; 
} 

回答

0

這似乎是有問題的按鈕股與radioGroup中的ID的ID,造成線

radioGroup.setId(question); 

爲什麼要這樣導致按鈕被粘ISN」對我清楚。如果您將該行更改爲

radioGroup.setId(radioGroup.getChildCount()); 

因此給它一個非衝突ID,所有按鈕都可以正常工作。

+0

太棒了! - 奇蹟般有效。謝謝 – 2012-03-11 15:00:17

+0

很高興幫助。好問題,小而獨立的例子 - 剪切,粘貼並運行它來查看問題。如果只有更多的海報花費同樣的麻煩。 – NickT 2012-03-11 15:04:26