4

This is my code and it doesn't work for me. I use code from this example.

Xml -

<android.support.v7.widget.SwitchCompat
            android:id="@+id/visibility_switch"
            android:layout_width="wrap_content"
            android:layout_height="55dp"
            android:layout_marginRight="@dimen/mat_card_padding"
            app:showText="false" />

And code:

mVisibilitySwitchCompat = (SwitchCompat) findViewById(R.id.visibility_switch);
mVisibilitySwitchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {             

                    // this method doesn't work!

                    if (isChecked) {
                        mVisibilityTextView.setText(getString(R.string.visibility_on));
                    } else {
                        mVisibilityTextView.setText(getString(R.string.visibility_off));
                    }
                }
            });
Artem
  • 4,569
  • 12
  • 44
  • 86

1 Answers1

1

Instead of using a listener, try the setTextOff() and setTextOn() methods. The Switch will automatically handle setting the correct one when the checked state changes.

RussHWolf
  • 3,555
  • 1
  • 19
  • 26
  • Can I catch switch events or click on the SwitchCompat? – Artem Nov 16 '15 at 15:02
  • @Artem Yes you should be able to do most things you can do with any other View. It's just that it's automatically handling the text it displays so your `setText()` calls get ignored or overridden. – RussHWolf Nov 16 '15 at 15:06