Basic Concept of ToggleButton Control in Android

In this tutorial basic concepts of ToggleButton control of Android is shown.

Code:

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” >

<TextView
android:id=”@+id/textView1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentLeft=”true”
android:layout_alignParentTop=”true”
android:layout_marginLeft=”60dp”
android:layout_marginTop=”85dp”
android:text=”Wifi” />

<ToggleButton
android:id=”@+id/tb”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignBaseline=”@+id/textView1″
android:layout_alignBottom=”@+id/textView1″
android:layout_marginLeft=”38dp”
android:layout_toRightOf=”@+id/textView1″
android:onClick=”onToggle”
android:text=”ToggleButton”
android:textOff=”Wifi Off”
android:textOn=”Wifi On” />

</RelativeLayout>

MainActivity.java

package com.example.demo;

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

public class MainActivity extends Activity{

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

public void onToggle(View v)
{
boolean op=((ToggleButton)v).isChecked();
if(op)
{
Toast.makeText(getApplicationContext(),”Wifi On”,Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(),”Wifi Off”,Toast.LENGTH_LONG).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

Add a Comment

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