Wednesday, 19 June 2013

Toggle button in ANDROID - An alternative to radio button

Toggle Button is a special button that has two states  for eg :"on" and "off".It can be an alternative to Radio Buttons.
Below are some methods mentioned in this example :
setOnClickListener – Used to register a callback whenever view is clicked
setChecked() – used to mark toggle button as checked/unchecked
setTextOn() – used to display text on toggle button whenever it is CHECKED
setTextOff() – used to display text on toggle button whenever it is UnCHECKED.

public class MainActivity extends Activity {
 ToggleButton toggle;
 protected void onCreate(Bundle savedInstanceState) {

  toggle = (ToggleButton) findViewById(;
  // you can set text accordingly when checked or not
  toggle.setTextOn("Toggle is Checked");
  toggle.setTextOff("Toggle is not Checked");
  // you can set if toggle to be checked or not
  toggle.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
    if (toggle.isChecked()) 
                    Toast.makeText(MainActivity.this, "is checked", Toast.LENGTH_SHORT).show();
                    Toast.makeText(MainActivity.this, "is not checked", Toast.LENGTH_SHORT).show();
 } }

No comments:

Post a Comment