Posts Tagged Button in android

Toggle Button in android

Today I thought of posting something which I came across recently. Toggle button.

As its name suggests, it toggles or switches between two states namely, ‘on’ and ‘off’. It is similar to a radio button.

Now, let’s see how this is implemented. I’ve given a simple example below to make you understand Toggle button easily.

Firstly let’s go to our UI part. Inside our XML file we can add ToggleButton widget and set its attributes.

The XML code is shown below:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
          <ToggleButton
              android:id="@+id/tglbtn"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textOn="ON"
              android:textOff="OFF"
              />
</LinearLayout>

The attribute   android:textOn=”ON” means  that the text on the button is  ‘ON’ when the it is in the ‘on’ state and   android:textOff=”OFF” specifies that the text on the button is ‘OFF’ when it is in the ‘off’ state.

Next step.

When the user clicks the button some action has to be done.

Here, I’ve given a Toast when the user clicks the button.

Here is the code. Just have a look.

package com.deepthi.mytogglebutton;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MyToggleButtonActivity extends Activity {
    /** Called when the activity is first created. */
    ToggleButton toggle;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        toggle=(ToggleButton)findViewById(R.id.tglbtn);
        toggle.setOnClickListener(new OnClickListener() {
              public void onClick(View v) {
               // TODO Auto-generated method stub
              if(toggle.isChecked())
              {
               Toast.makeText(getApplicationContext(), "The state is changed to on", Toast.LENGTH_LONG).show();
               }
                else
                {
                  Toast.makeText(getApplicationContext(), "The state is changed to off", Toast.LENGTH_LONG).show();
                 }
                 }
                 });
    }
}

The Output looks like this:

When checked:

When Unchecked:

Advertisements

, , , , , ,

6 Comments