Toggle Button Widget

Next component that you may use is the toggle button. This can be useful if you need a button that can be either be on or off.

Below is the steps to create the example for this toggle button:

Step 1: Project Structure

Step 2: Layout (activity_main.xml)

<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android

xmlns:tools=”http://schemas.android.com/tools

android:layout_width=”match_parent”

android:layout_height=”match_parent”

android:paddingBottom=”@dimen/activity_vertical_margin”

android:paddingLeft=”@dimen/activity_horizontal_margin”

android:paddingRight=”@dimen/activity_horizontal_margin”

android:paddingTop=”@dimen/activity_vertical_margin”

tools:context=”.MainActivity” >

<ToggleButton android:id=”@+id/togglebutton”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:textOn=”WI-FI On”

android:textOff=”WI-FI Off”/>

</RelativeLayout>

Step 3: Source Code (MainActivity.java)

package com.example.hellotogglebutton;

import android.os.Bundle;

import android.app.Activity;

import android.widget.Toast;

import android.widget.ToggleButton;

import android.view.View;

import android.view.View.OnClickListener;

public class MainActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

final ToggleButton togglebutton = (ToggleButton) findViewById(R.id.togglebutton);

togglebutton.setOnClickListener(new OnClickListener(){

public void onClick(View v){

//Perform action on clicks

if (togglebutton.isChecked()){

Toast.makeText(getApplicationContext(),”Checked”, Toast.LENGTH_SHORT).show();

}else{

Toast.makeText(getApplicationContext(), “Not Checked”, Toast.LENGTH_SHORT).show();

}

}

});

}

}

Step 4: Run (Output)

Leave a Reply

Your email address will not be published. Required fields are marked *