An Android CheckBox OnClickListener example (and identityHashCode)

Here’s some source code that shows how to add an Android OnClickListener to a CheckBox:

checkBox.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Log.i(TAG, String.format("checkbox onClick, isSelected: %s, identityHashCode: %s", checkBox.isSelected(), System.identityHashCode(checkBox)));

The OnClickListener code is straightforward, so I won’t explain it; I’m just putting it here so I can find it easily in the future, like a code snippet manager.

One other thing to note is the use of the identityHashCode. I did that because I was having a weird problem working with Android checkboxes. The short story is that I kept trying to use the isSelected method on each CheckBox, which I should have been using isChecked. I used the identityHashCode method to help troubleshoot the problem.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.