A Radio button is similar to check boxes where in it has two
states checked or unchecked. So what is
the difference between a radio button and a checkbox, well it’s simple in case
of checkbox user can uncheck it which is not possible in case of radio buttons.
Hence when you use radio buttons use it in Radio Groups where in at any time
only one option can be selected.
In this
post I have created 2 radio buttons called ‘India’ and ‘New Zealand’, a Button
called ‘Done’. Once a user clicks on the ’Done’ button it should show ‘You
Selected -<Country Name>’.
Create a project and add the following –
Main.xml - Open the main.xml file in layout folder. Remove
the default textview. Add a Large Text and add the app name to this. Then drag
a medium text and have a label ‘Select Country’. Then add 2 radio buttons and
call them India and New Zealand. Add a button and label it ‘Done’. On clicking
the button you need to display the country which has been selected, so include
a text view in it which you will set using java code.
The layout should like the one below –
RadioButton_Activity.Java – Open the class file RadioButton_Activity.Java
in src folder. Here you need to declare and bind the Radio Button which you
have created in the Main.xml file. Hence you need to add code
R1=(RadioButton) findViewById(R.id.radioButton1);
R2=(RadioButton) findViewById(R.id.radioButton2);
Then you need to add a button called ‘Done’ and a listener
which will set the text to ‘You Selected -<Country Name>’ as shown in
the code below
Done=(Button)
findViewById(R.id.button1);
tv=(TextView)
findViewById(R.id.textView3);
Done.setOnClickListener(new
View.OnClickListener() {
@Override
public
void onClick(View V) {
if(R1.isChecked()){
tv.setText("You
Selected - "+R1.getText());
}
if(R2.isChecked()){
tv.setText("You
Selected - "+R2.getText());
}
}
});
The code will finally look like
the one below
And, we are done with coding,
simple wasn’t it. Now lets see if it works, right click on the project and
click on run as android application. The initial screen which you get will be
as shown in the below
Now click on a country and click
on the Done button, in this case I have clicked on India and the result is as
shown below.
Well that was easy, I will tell
how to use radio groups in my next post.
No comments:
Post a Comment