Basic Concept of RadioButton Control in Android

In this tutorial basic concepts of RadioButton control of Android is shown.

Code:

radio.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<RadioGroup xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent” >

<TextView
android:id=”@+id/textView1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Gender” />

<RadioGroup
android:id=”@+id/radioGroup1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” >

<RadioButton
android:id=”@+id/m”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:checked=”true”
android:onClick=”onSelect”
android:text=”Male” />

<RadioButton
android:id=”@+id/f”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:onClick=”onSelect”
android:text=”Female” />
</RadioGroup>

<Button
android:id=”@+id/b1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:onClick=”onSubmit”
android:text=”Submit” />

<TextView
android:id=”@+id/t”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”TextView” />

</RadioGroup>

 

MainActivity.java

package com.example.demo;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;

public class MainActivity extends Activity{

TextView t;
String gen;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.radio);
t=(TextView)findViewById(R.id.t);
}

public void onSelect(View v)
{
boolean op=((RadioButton)v).isChecked();
switch(v.getId())
{
case R.id.m:
gen=”Male”;
break;
case R.id.f:
gen=”Female”;
break;
}
}

public void onSubmit(View v)
{
t.setText(gen);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

https://youtu.be/LQEvnPa9KfY

Add a Comment

Your email address will not be published. Required fields are marked *