Toggle Button

Toggle Button is useful for check/uncheck state of the button. Toggle button is separate from normal button.

activity_main.xml

This xml shows two toggle buttons and one single button for our layout.

      
      
      
          
      
          
      
        
MainActivity.java

Lets write a code for set toggle button on/off state.

package com.example.codebridgetogglebuttonexample;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity {
private ToggleButton toggle1, toggle2;
private Button btnSubmit;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

addListenerOnButtonClick();
}
public void addListenerOnButtonClick(){
toggle1=(ToggleButton)findViewById(R.id.toggle1);
toggle2=(ToggleButton)findViewById(R.id.toggle2);
btnSubmit=(Button)findViewById(R.id.btn_submit);

btnSubmit.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
StringBuilder result = new StringBuilder();
result.append("ToggleButton1 : ").append(toggle1.getText());
result.append("\nToggleButton2 : ").append(toggle2.getText());
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}