How do I check if a switch is activated?

Asked

Viewed 151 times

1

I’m trying to do a show that has some elements of the house, like lamps. On a screen I want you to show all the elements, whether these are on or off. I own some Switchs and want to put a text on the main screen equivalent to their status.

This is my XML with the switch:

<Switch
android:id="@+id/switch1"
android:layout_width="140dp"
android:layout_height="50dp"
android:text="Lampada" />

And here I try to check his status:

public void homeFragment () {

    switchQuarto = view.findViewById(R.id.switch1);
    elemento = view.findViewById(R.id.elemento);
    status = view.findViewById(R.id.status);
    elemento.setText(Html.fromHtml("Status da Lampada: "));
    if (switchQuarto.isActivated()) {
        status.setText(Html.fromHtml("Ligada"));
    } else {
        status.setText(Html.fromHtml("Desligada"));
    }
}

It hangs on the switchQuarto.isActivated(), how can I do this check ?

1 answer

0


You have to add a Switch is the best way in my opinion, because so whenever it changes, it triggers an action.

switchQuarto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(switchQuarto.isChecked()){
                   // Aqui você faz a ação
                   status.setText(Html.fromHtml("Ligada"));
                } else {
                   status.setText(Html.fromHtml("Desligada"));
                }
            }
        });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.