2017-09-15 127 views
0

我一次只想選擇一個單選按鈕,但選中其中一個單選按鈕後,如果我點擊其中一個按鈕,他們都被選中,我該如何解決這個問題。 Screenshot of the activity main只選擇一個單選按鈕

我MainActivity.java代碼

public class MainActivity extends AppCompatActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

} 

public void onClick(View view) { 
    TextView text=(TextView)findViewById(R.id.txt1); 
    text.setText("Wrong Answer"); 
} 

public void onClick1(View view) { 
    TextView text=(TextView)findViewById(R.id.txt1); 
    text.setText("You are Right"); 
} 
} 
+4

一個字'Radiogroup' –

+0

只需使用RadioGroup中,往其中加單選按鈕 –

回答

0

單選按鈕應該是RadioGroup中的直接孩子,否則分組不起作用。

<RadioGroup 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:id="@+id/radioGroup"> 
    <RadioButton 
     android:layout_width="0dp" 
     android:layout_weight="50" 
     android:layout_height="wrap_content" 
     android:text="Debit" 
     android:id="@+id/rDebit" 
     android:checked="false" 
     /> 

    <RadioButton 
     android:layout_width="0dp" 
     android:layout_weight="50" 
     android:layout_height="wrap_content" 
     android:text="Credit" 
     android:id="@+id/rCredit" 
     android:checked="false" /> 

</RadioGroup> 

而且在Java文件

RadioGroup radioGroup; 

radioGroup = (RadioGroup) findViewById(R.id.radioGroup); 

做點什麼

if (radioGroup.getCheckedRadioButtonId() == R.id.rCredit) 
{ 
// do something 
} 
0

接受的答案被刪除,無法復原。可能因爲它僅僅是一個外部網站的鏈接。所以這裏有一個更詳細的版本:

你需要在佈局文件中將同一個RadioGroup中的單選按鈕分組。

在這裏看到:https://developer.android.com/guide/topics/ui/controls/radiobutton.html

適用於您的問題,這可能是這樣的:

<RadioGroup 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"> 

    <RadioButton 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:onClick="onClick" 
     android:text="Dennis Ritchie" /> 

    <RadioButton 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:onClick="onClick1" 
     android:text="James Gosling" /> 
</RadioGroup> 
相關問題