Saturday, April 18, 2015

ToggleButton

1. Drag a toggle button to activity_main.xml and the XML code becomes:

    <ToggleButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New ToggleButton"
        android:id="@+id/toggleButton"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="35dp"
        android:checked="false" />

2. Write the code as below to inform the user the toggle button is ON/OFF with toast:

package com.example.kiosk.togglebutton;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.ToggleButton;

import static android.widget.ToggleButton.*;


public class MainActivity extends ActionBarActivity {

    ToggleButton myToggleButton;

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

        myToggleButton = (ToggleButton)findViewById(R.id.toggleButton);

        myToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Toast.makeText(getApplicationContext(), "ON!!", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "OFF!!", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

============================
Toggle Button in iOS Swift

No comments:

Post a Comment