Tuesday, August 18, 2015

// //

Add and implement toggle button in actionbar

Hi guys let me show you how to add the switch or toogle button

into the action bar.

Let me show you:

in menu folder create a new xml and named it menu.

And then copy and paste this code:



This time we have created a new item called switchid..

And then navigate to your layout folder make a new xml file
and name it switch_layout.xml
Here's the code:


This time we have added a switch..
And in your activity_main.xml just add this code:


Now we're nearly done..
In your MainActivity class copy and paste this code:

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.provider.Settings.SettingNotFoundException;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;
import android.widget.Toast;

public class MainActivity extends Activity {
  Switch switchAB;
  protected void onCreate(Bundle savedInstanceState) {
  public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.menu, menu);
  switchAB = (Switch)menu.findItem(R.id.switchId)

OnCheckedChangeListener() {
  public void onCheckedChanged(CompoundButton 

  boolean isChecked) {
  if (isChecked) {
  Toast.makeText(getApplication(), "ON", 

  } else {
  Toast.makeText(getApplication(), "OFF", 

  return true;

Now were finished! Run it on your emulator! Please ensure the android manifest