0

I am implementing a switch button that can remotely turn on or off a light.

Whenever the switch button is pressed, a HTTP request will be sent to the server, and a response will be sent back.

The requirement is:

While the app is waiting for the response, the switch button turns yellow.

If the response is 200 OK, the button turns green.

If the response is denied or times out, the button turns red.

I am using the default switch button. It does not allow me to change the color dynamically and I have been looking around and could not find anything that can be used for my app.

How am i able to achieve this multi-state switch button?

齐天大圣
  • 1,169
  • 5
  • 15
  • 36

1 Answers1

0

You can can change the colour like this. I just tested and it works:

// Assuming ToggleButton with id "toggleButton"
final ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                // The toggle is enabled
                toggle.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
            } else {
                // The toggle is disabled
                toggle.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorAccent));
            }
    }
});

Just as an example. Is that what you mean? Of course you can make up your own colours in the "colors.xml" file.

Michael Vescovo
  • 3,741
  • 4
  • 32
  • 45