Skip to content Skip to sidebar Skip to footer

Changing Two Button Into A Toggle Button

I have a Flashlight code that use two buttons (on_btn and off_btn) to turn on and turn off the Flashlight. How can I associate them in a single button? Very novice can you give el

Solution 1:

use the button to flip a boolean value, and change your flashlight to go on and off accordingly.

privateboolean isActive;

//this will be inside your onCreate...
button.setOnClickListener(newView.onClickListener() {
    publicvoidonClick(View v) {
        flipSwitch();
        processClick();
    }
}

//these will be outside your onCreatepublicvoidflipSwitch() {
    isActive = !isActive;
}

publicvoidprocessClick() {
    if(isActive) {
        //button is clicked on
    }
    else {
        //button is clicked off
    }
}

Solution 2:

You could always use the Toggle Button instead of two buttons. It's very "Android formal".

//Create a toggle buttonToggleButtontg= (ToggleButton) findviewbyId(R.id.togbut);

//Implement onClickListener
tg.setOnClickListener(newOnClickListener()
{
    @OverridepublicvoidonClick(View v){
        //Flip on or off
    }
});

In the onClick() method, you can do what you need to do according to what your app is suppose to do when the button is on or off.

In the xml layout, you say what the toggle button says when it's on and off.

<ToggleButton
    android:id="@+id/togbut"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOn="Button On"
    android:textOff="Button Off"
    android:checked="true" />

When you click the toggle button, it will automatically change the text and toggle.

Here's a good example: http://www.mkyong.com/android/android-togglebutton-example/

Hope that helps!

Post a Comment for "Changing Two Button Into A Toggle Button"