How do I check if a switch is enabled?

1

I'm trying to make a program that has some elements of the house such as bulbs. On a screen I want it to show all the elements, whether those are on or off. I have some switches and I want to put a text on the main screen equivalent to their status.

This is my XML with switch :

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

And here I try to check the status of it:

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 switchQuarto.isActivated() , how can I do this check?

    
asked by anonymous 28.09.2018 / 02:55

1 answer

0

You have to add a listener 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"));
                }
            }
        });
    
29.09.2018 / 02:19