2017-02-25 8 views
-1

2つのボタン、男性と女性があり、私がしたいことは、ユーザーが男性ボタンを選択した場合、背景色、それがRadioGroupとして機能する方法を変更することです男性または女性のみを選択できます。2つのボタンの状態を作成する方法

私はあなたが

ため
<RadioGroup 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:orientation="vertical"> 
<RadioButton android:id="@+id/radio_pirates" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/pirates" 
    android:onClick="onRadioButtonClicked"/> 
<RadioButton android:id="@+id/radio_ninjas" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/ninjas" 
    android:onClick="onRadioButtonClicked"/> 
</RadioGroup> 

とアクティビティで

public void onRadioButtonClicked(View view) { 
// Is the button now checked? 
boolean checked = ((RadioButton) view).isChecked(); 

// Check which radio button was clicked 
switch(view.getId()) { 
    case R.id.radio_pirates: 
     if (checked) 
      // Pirates are the best 
     break; 
    case R.id.radio_ninjas: 
     if (checked) 
      // Ninjas rule 
     break; 
} 
} 

以下のように簡単に実現することができますが、Buttons

の代わりにRadioButtonを使用することをお勧め要件のこれらの種類の通常

<LinearLayout 
     android:paddingTop="20dp" 
     android:layout_gravity="center" 
     android:weightSum="2" 
     android:orientation="horizontal" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"> 
     <Button 
      android:id="@+id/btn_male" 
      android:textColor="@color/White" 
      android:background="@color/colorPrimaryDark" 
      android:layout_gravity="end" 
      android:text="@string/male" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:onClick="genderPerson" 
      /> 

     <Button 
      android:id="@+id/btn_female" 
      android:textColor="@color/White" 
      android:background="@color/colorPrimaryDark" 
      android:text="@string/female" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:onClick="genderPerson" 
      /> 
    </LinearLayout> 
+0

二つのボタンで、そううん、私は同じことをしましたが、他のもののためにRADIOGROUP –

答えて

1

詳細はこちらを参照 Documentation

この完全な例example

+0

を使用していますが、デザインは、このようにする必要があり、「RADIOGROUPとしてそれが動作する方法」 、私は1つのクリックを取得し、他の無効にするいくつかのロジックを作成しようとしていたが、それは動作しません! –

+0

'RadioButton'の背景を' Button'のように変更できます – Jayanth

関連する問題