Tuesday, 17 May 2016

Toogle Button In Android

A toggle button allows the user to change a setting between two states.
You can add a basic toggle button to your layout with the ToggleButton object. Android 4.0 (API level 14) introduces another kind of toggle button called a switch that provides a slider control, which you can add with a Switch object.
Strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ToggleButton</string>
    <string name="hello_world">Toggle Demo Example</string>

</resources>
Activity_Toggle.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/hello_world" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:gravity="left"
        android:textColor="#555ccc"
        android:textSize="23sp" >

        <requestFocus />
    </EditText>

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:checked="true"
        android:textOff="Decripted"
        android:textOn="Encripted" />

</LinearLayout>

ToggleActivity.Java

package com.example.togglebutton;

import android.app.Activity;
import android.os.Bundle;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ToggleButton;

public class ToggleActivity extends Activity {
ToggleButton tb;
EditText et;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_toggle);
        
        tb=(ToggleButton) findViewById(R.id.toggleButton1);
        et=(EditText) findViewById(R.id.editText1);
        
        tb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(tb.isChecked()){
et.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_NUMBER_VARIATION_PASSWORD);
}
else{
et.setInputType(InputType.TYPE_CLASS_TEXT);
}
}
});
    }
}

Output


Download Source code


No comments:

Post a Comment

Ads Inside Post