2017-02-25 21 views
-1

我有兩個按鈕,男性和女性,我想要做的是,如果用戶選擇一個男性按鈕,更改背景顏色,它作爲一個RadioGroup的方式,只需選擇男性或女性。如何創建兩個按鈕的狀態android

<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

通常這些樣的要求,我建議你使用RadioButton代替Buttons

就可以實現輕鬆地像下面

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

爲更多信息請參考 Documentation

這個完整的例子example

+0

是啊,我也做了同樣的事情,但對於其他的事情,但設計必須是這樣的,有兩個按鈕「它可以作爲一個RadioGroup中的方式」 ,我試圖創建一些邏輯來獲得點擊一個並禁用另一個,但它不起作用! –

+0

你可以將'RadioButton'的背景改爲'Button' – Jayanth