2014-01-18 40 views
5

如何確保用戶每個radiogroup至少檢查一個單選按鈕。像我有這樣的RadioGroup中:從android的每個radiogroup中選擇至少一個單選按鈕?

<RadioGroup 
    android:id="@+id/myradio_group_one" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" > 

    <RadioButton 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="first" 
     android:checked="true" /> 

    <RadioButton 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="second" /> 

    <RadioButton 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="third" /> 

    <RadioButton 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="fourt" /> 
</RadioGroup> 

<RadioGroup 
    android:id="@+id/myradio_group_two" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" > 

    <RadioButton 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="first" 
     android:checked="true" /> 

    <RadioButton 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="second" /> 

    <RadioButton 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="third" /> 

    <RadioButton 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="fourt" /> 
</RadioGroup> 

我要檢查編程如果用戶至少選擇一個單選按鈕或不?

回答

6
RadioGroup g = (RadioGroup) findViewById(R.id.rBtnDigits); 

// Returns an integer which represents the selected radio button's ID 
int selected = g.getCheckedRadioButtonId(); 

// Gets a reference to our "selected" radio button 
RadioButton b = (RadioButton) findViewById(selected); 

// Now you can get the text or whatever you want from the "selected" radio button 
b.getText(); 
+0

沒有提到的,我需要這個來自編程。 – androidcodehunter

2

這是我在測驗的應用程序的一個使用的代碼..看一看代碼,如果這有助於..

private boolean checkAnswer(){ 
     String answer = getSelection(); 
     if(answer==null) { 
      Log.d("Questions", "No checkbox selected"); 
      return false; 
     } 
     else { 
     // Do your stuff here 
      return true; 
     } 

    } 


    private String getSelection(){ 


     if (c1.isChecked()) 
     { 
      return c1.getText().toString(); 
     } 
     if (c2.isChecked()) 
     { 
      return c2.getText().toString(); 
     } 
     if (c3.isChecked()) 
     { 
      return c3.getText().toString(); 
     } 
     if (c4.isChecked()) 
     { 
      return c4.getText().toString(); 
     } 

     return null; 

    } 
3
if (radioGroup.getCheckedRadioButtonId() != -1) 
{ 
    // hurray at-least on radio button is checked. 
} 
else 
{ 
    // pls select at-least one radio button.. since id is -1 means no button is check 
} 
相關問題