Reputation: 453
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.
Upvotes: 7
Views: 21107
Reputation: 5260
Hi please have a look at http://custom-android-dn.blogspot.in/2013/01/how-to-use-and-custom-switch-in-android.html
we can do this in given way
switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (buttonView.isChecked()){
//do something }
else{
//do something
}
}
});
Upvotes: 0
Reputation: 6709
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
}
});
Upvotes: 11