Translate

Sunday, April 7, 2019

Android | Working With RadioGroup and RadioButton





1. activity_main.xml

<?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"
android:layout_margin="10dp"
android:orientation="vertical"
tools:context=".MainActivity">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Gender"
android:textSize="30sp"
android:textStyle="bold" />

<RadioGroup
android:id="@+id/rg"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<RadioButton
android:id="@+id/rbmale"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Male"
android:textStyle="bold" />

<RadioButton
android:id="@+id/rbfemale"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Female"
android:textStyle="bold" />

</RadioGroup>

</LinearLayout>

2. MainActivity.java

package com.example.radiobutton;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

RadioGroup rg;
RadioButton rbmale, rbfemale;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

rg = findViewById(R.id.rg);
rbmale = findViewById(R.id.rbmale);
rbfemale = findViewById(R.id.rbfemale);

rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (rbmale.isChecked()) {
Toast.makeText(MainActivity.this, "" + rbmale.getText().toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "" + rbfemale.getText().toString(), Toast.LENGTH_SHORT).show();
}
/*if (checkedId == R.id.rbmale) {
Toast.makeText(MainActivity.this, "Male", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Female", Toast.LENGTH_SHORT).show();
}*/
}
});
}
}


Click here to download source code

No comments:

Post a Comment