Android tutorial for beginner part 15, Radiogroup

  • 23 April 20
  • Posted By : Admin
  • 108 Hits
  • 10 Comment

We will see here how to create a radiogroup and make selection action to test those.

}

Java code

create a java file name MainActivity.java

copy below code to the java file

package com.salam.radiogroup; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; public class MainActivity extends AppCompatActivity { public RadioGroup radioGroup; public RadioButton radioButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); radioGroup = findViewById(R.id.radioGroup); } public void radioButtonfunc(View view){ int selectedBtn = radioGroup.getCheckedRadioButtonId(); radioButton = findViewById(selectedBtn); Toast.makeText(this, "Country name: "+radioButton.getText(), Toast.LENGTH_SHORT).show(); } }

Create xml file if you dont have already

If you dont have xml file then Create one activity_main.xml file and then paste below code.

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical" android:gravity="center"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Radio group project" android:textSize="24sp" android:textColor="#000" /> <RadioGroup android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/radioGroup"> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="radioButtonfunc" android:text="Bangladesh"/> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="radioButtonfunc" android:text="India"/> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="radioButtonfunc" android:text="Pakstan"/> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="radioButtonfunc" android:text="Bhutan"/> </RadioGroup> </LinearLayout>