C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Android RadioButtonRadioButton is a two states button which is either checked or unchecked. If a single radio button is unchecked, we can click it to make checked radio button. Once a radio button is checked, it cannot be marked as unchecked by user. RadioButton is generally used with RadioGroup. RadioGroup contains several radio buttons, marking one radio button as checked makes all other radio buttons as unchecked. Example of Radio ButtonIn this example, we are going to implement single radio button separately as well as radio button in RadioGroup. activity_main.xmlFile: activity_main.xml Activity classFile: MainActivity.java package example.TheDeveloperBlog.com.radiobutton; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button button; RadioButton genderradioButton; RadioGroup radioGroup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); radioGroup=(RadioGroup)findViewById(R.id.radioGroup); } public void onclickbuttonMethod(View v){ int selectedId = radioGroup.getCheckedRadioButtonId(); genderradioButton = (RadioButton) findViewById(selectedId); if(selectedId==-1){ Toast.makeText(MainActivity.this,"Nothing selected", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(MainActivity.this,genderradioButton.getText(), Toast.LENGTH_SHORT).show(); } } } Output
Next TopicAndroid Dynamic RadioButton
|