开发者

What makes a button switch and keep color on click?

开发者 https://www.devze.com 2023-03-29 23:41 出处:网络
I want to create a Button that behaves like a switch. It should change its color when the user clicks it, and keep the color.

I want to create a Button that behaves like a switch.

It should change its color when the user clicks it, and keep the color.

So the button is white at first and when the user clicks it, the color changes to black. When the user clicks it again it switches back to white and so on.

I tried it with a simple if else construct but only managed to get the button to be white at first and when being clicked change to black, but it won´t change back to white when clicked again.

Here´s the code so far. I guess it´s a dumb simply mistake but can´t seem to get through with it. "changecolor" is a variable I declared myself.

// Select Button Safe or At-Risk
final Button button7 = (Button) findViewById(R.id.SafeBT);
button7.setOnClickListener(new OnClickListener(){

    public void onClick(View v) {
        // Perform action on clicks, change color
   开发者_如何学Python     if (changecolor == 0) {
            button7.setBackgroundColor(color.black);
            changecolor = 1;          
        } else {
            button7.setBackgroundColor(color.white);
            changecolor = 0; 
        }    
    }

});

Tanks for advice and help in advance.


where you have declared your variable changecolor?? .

Second thingis that you can simply an UI Element which call it : ToggleButton , it is like a Switch Button ON/OFF . is that what you want ? see this link : http://developer.android.com/reference/android/widget/ToggleButton.html

0

精彩评论

暂无评论...
验证码 换一张
取 消