Clicking on ClickableSpan in CheckBox changes its state
Asked Answered
H

2

5

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.

Hardhack answered 13/3, 2018 at 9:57 Comment(0)
I
2

Are you using a solution similar to that outlined in https://mcmap.net/q/293430/-how-do-i-make-a-portion-of-a-checkbox-39-s-text-clickable? 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.

Inwards answered 5/1, 2019 at 22:55 Comment(0)
B
-2

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.

Blandish answered 23/10, 2019 at 20:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.