Create Image radio button in Android (Java)
Step1(XML Code)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="Select Gender"
android:textColor="@color/RedDark"
android:textSize="25sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<LinearLayout
android:id="@+id/imgMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginTop="30dp"
android:src="@drawable/Male" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Male"
android:textColor="@color/RedDark"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:id="@+id/imgFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:orientation="vertical">
<ImageView
android:layout_width="150dp"
android:layout_height="150dp"
android:src="@drawable/Female" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Female"
android:textColor="@color/RedDark"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
Step 2(Java Code)
LinearLayout Male, Female
Male= findViewById(R.id.imgMale);
Female= findViewById(R.id.imgFemale);
Male.setOnClickListener(v -> {
Male.setBackgroundResource(R.color.RedDark);
Toast.makeText(getApplicationContext(),"Male Selected",Toast.LENGTH_SHORT).show();
});
Female.setOnClickListener(v -> {
Female.setBackgroundResource(R.color.RedDark);
Toast.makeText(getApplicationContext(),"Female Selected",Toast.LENGTH_SHORT).show();
});
Finish