Kamo Spertsian
Kamo Spertsian

Reputation: 825

Clicking on ClickableSpan in CheckBox changes its state

I've got an ImageSpan and ClickableSpan in my checkbox to display icon at the end of checkbox text and handle clicking on it. But clicking on it changes checkbox checked state, which is not needed.

How can I prevent changing checkbox state when user clicks on ClickableSpan?

Simply I need some equivalent of cancelPendingInputEvents() method for API 16+. Also I don't want to separate checkbox with checkbox and textview.

Upvotes: 5

Views: 1360

Answers (2)

rana
rana

Reputation: 1862

If you set your Checkbox text with Spannable String with the onclick listener inside the spannable sub text. All you need to do is add this line,

checkBoxView.setMovementMethod(LinkMovementMethod.getInstance());

You are good to go.

Upvotes: -2

Grzegorz Adam Hankiewicz
Grzegorz Adam Hankiewicz

Reputation: 7691

Are you using a solution similar to that outlined in https://stackoverflow.com/a/47166879/172690? If so, I have found the following onClick implementation to be funcional:

        @Override
        public void onClick(View widget) {
            // Prevent CheckBox state from being toggled when link is clicked
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                widget.cancelPendingInputEvents();
            } else {
                if (widget instanceof CheckBox) {
                    CheckBox checkbox = (CheckBox) widget;
                    boolean state = checkBox.isChecked();
                    checkBox.post(new Runnable() {
                        @Override public void run() {
                            checkBox.setChecked(state);
                        }
                    });
                }
            }
            // Do action for link text...
        }

Essentially the state is saved during the handling of the click and then posted so it can be restored. As you can imagine, the checkbox does flash and animate while pressing the clickable spannable. However, even the cancelPendingInputEvents branch flashes the checkbox when the link is touched, so my guess is this is the best you can do short of writing your own checkbox widget.

Upvotes: 2

Related Questions