Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android.widget.Switch toggled event listener?

Tags:

android

adt

I have tried the code in the answer of android-widget-switch-on-off-event-listener, but the post doesn't say anything about the error I got trying to use it.

At the second line of the suggested code:

    switch1 = (Switch) findViewById(R.id.switch1);

    switch1.setOnCheckedChangeListener(new OnCheckedChangedListener() { //This line has the error
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            aTextView.setText("Switch was toggled");
        }
    });

This error triggers

The method setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener) in the type CompoundButton is not applicable for the arguments (new OnCheckedChangedListener(){})

How can I fix this? All I want to do is call a function when the switch changes - as opposed to when it is clicked. Thanks.

like image 506
kevbot Avatar asked Jan 09 '14 03:01

kevbot


Video Answer


1 Answers

Set the listener to this because your class implements compoundbutton like so...

switch1.setOnCheckedChangeListener(this);

Then add this method in your code...

    @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            boolean = isChecked;
            //whatever you want
        }

EDIT: if you havent implemented CompoundButton.OnCheckedChangedListener use this...

switch.setOnCheckedChangeListener(new OnCheckedChangeListener(

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                // TODO Auto-generated method stub

            }

        });
like image 148
Ogen Avatar answered Sep 20 '22 16:09

Ogen