Select the gender in android, such as radioButton
I’m working on a simple program where I want to be able to select my gender like radio button behavior, you can choose female or male, and the other choice should be unchecked. I have separate images of buttons, pressed and unpressed.
I’ve stored the state in a selector file:
button_female.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:drawable="@drawable/gender_f"/>
<item android:state_pressed="true" android:drawable="@drawable/gender_f" />
<item android:drawable="@drawable/gender_f_notpressed" />
</selector>
In layout/settings_activity.xml:
<Button
android:layout_width="130dp"
android:layout_height="130dp"
android:id="@+id/maleButton"
android:layout_alignParentTop="true"
android:layout_marginTop="80dp"
android:layout_marginLeft="220dp"
android:drawable="@drawable/button_male"
android:onClick="onGenderButtonClicked"
/>
In Activity, onClick is written
public void onGenderButtonClicked(View view) {
if(feButton.isPressed()){
maButton.setEnabled(false);
radioPressed = true;
} else if (maButton.isPressed()){
feButton.setEnabled(false);
radioPressed = true;
} else {
radioPressed = false;
}
}
However, this does not work for a number of reasons…
1: The picture on the button is not displayed, whether pressed or not.
2: My code is bad and the button doesn’t work as expected. I want them to behave like a radio group (you can choose male or female as your gender).
So I seem to have two questions here. Does anyone know of a good way to solve this problem? I’m new to writing Android apps…
Solution
If you need something like this:
You can use this layout:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=". MainActivity"
>
<RadioGroup
android:id="@+id/radioGrp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@drawable/gender_old"
android:paddingTop="64dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
>
<RadioButton
android:id="@+id/radioM"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:checked="true"
android:drawableRight="@drawable/male"
android:layout_weight="1"
android:textSize="14dp"
android:text="Male"
/>
<RadioButton
android:id="@+id/radioF"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:checked="false"
android:drawableRight="@drawable/female"
android:layout_weight="1"
android:textSize="14dp"
android:text="Female"
/>
</RadioGroup>
</RelativeLayout>