2017-09-15 5 views
0

Ich möchte nur eine Optionsschaltfläche nach der anderen auswählen, aber nachdem ich eine ausgewählt habe, wenn ich auf die andere Schaltfläche klicke, werden beide ausgewählt. Was kann ich tun, um dieses Problem zu lösen. Screenshot of the activity mainWählen Sie nur eine Optionsschaltfläche

Mein MainActivity.java Code ist

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

ein Wort 'Radiogroup' –

+0

Nur Radiogroup verwenden und fügen Sie Radiobuttons im Inneren –

Antwort

0

RadioButton- die direkte Kind von Radiogroup sein sollte, sonst Gruppierung funktioniert nicht.

<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> 

Und in Java-Datei

RadioGroup radioGroup; 

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

etwas tun

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

Die akzeptierte Antwort gelöscht und nicht wiederhergestellt werden können. Wahrscheinlich, weil es kaum mehr als ein Link zu einer externen Site war. Also hier ist eine detailliertere Version:

Sie müssen die Radioknöpfe innerhalb derselben RadioGroup in Ihrer Layoutdatei gruppieren.

Siehe hier: https://developer.android.com/guide/topics/ui/controls/radiobutton.html

auf Ihr Problem Angewandt dies könnte wie folgt aussehen:

<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> 
Verwandte Themen