Sunday, 14 June 2015

Toggle button in android -1

No comments
In this example,we learn use of toggle button in android. the toggle button is a special class to render a button which has only two states,like " On / Off "," 0 / 1 ","Yes / On","True / false" etc.It’s best switching buttons to turn on or turn off a function.here i show you a very simple example to display current status on click toggle button.

CREATE NEW ANDROID PROJECT

Step 1: Write code into activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ToggleButton" >
    </ToggleButton>


</LinearLayout>

Step 2: Write code into MainActivity.java


package dev.androidapplink.togglebutton_2;

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

public class MainActivity extends Activity {
/** Called when the activity is first created. */

ToggleButton tgbutton;

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

tgbutton = (ToggleButton) findViewById(R.id.toggleButton1);
tgbutton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (tgbutton.isChecked()) {

Toast.makeText(getApplicationContext(), "Toggle ON",
Toast.LENGTH_LONG).show();

} else {

Toast.makeText(getApplicationContext(), "Toggle OFF",
Toast.LENGTH_LONG).show();
}
}
});

// To set Toggle button checked/unchecked or default(true or false)
// tgbutton.setChecked(true);

}

}

Step 3: Now Run Your Project:




No comments :

Post a Comment

Follow me Share