Java 如何创建两个按钮的状态

Java 如何创建两个按钮的状态,java,android,Java,Android,我有两个按钮,男按钮和女按钮,我想做的是,如果用户选择一个男按钮,改变背景颜色,它作为一个放射组的工作方式,只需选择男按钮或女按钮 <LinearLayout android:paddingTop="20dp" android:layout_gravity="center" android:weightSum="2" android:orientation="horizontal" android:layou

我有两个按钮,男按钮和女按钮,我想做的是,如果用户选择一个男按钮,改变背景颜色,它作为一个放射组的工作方式,只需选择男按钮或女按钮

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

通常对于此类要求,我建议您使用
单选按钮
而不是
按钮

您可以像下面这样轻松地实现

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