OnCheckedChangeListener or OnClickListener with if statement for CheckBox's? What is the difference in functionality?
Asked Answered
D

1

9

Hello I'm creating an android application that uses checkbox's, i'm wondering if it is better to use an OnCheckedChangeListener to do something when the state of the checkbox is changed or if it would be better to use an OnClickListener with an if statement inside it that is executed everytime the checkbox is checked or unchecked? Thanks

Delorisdelorme answered 21/3, 2014 at 16:21 Comment(0)
I
15

With OnCheckedChangeListener you receive an event whenever the checked status changes, even when done in code by using .setChecked().

Depending on what you are doing this can lead to unexpected behavior (for example when you have a checkbox in a listview, the view is recycled and the checkbox state is modified programmatically, it looks exactly the same way as if the user had clicked it).

Therefore, when you are writing code that is supposed to react to a user who clicked the checkbox you should use OnClickListener.

Intertidal answered 21/3, 2014 at 16:26 Comment(2)
ah i see! So an OnCheckedChangeListener would execute the same code everytime the state of it changes. Where as an OnClickListener with an if statement inside would be able to check the state of the checkbox every time it is pressed?Delorisdelorme
Yes. The OnCheckedChangeListener supplies a boolean variable isChecked while in the OnClickListener you would fetch that information using ((CheckBox) v).isChecked() (if v is the View that is passed as the parameter). But the main point is that the latter is meant to be used with User (finger) interaction.Intertidal

© 2022 - 2024 — McMap. All rights reserved.