Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add click action for the ImageSpan

Tags:

android

I have a ImageSpan set in the TextEdit. And I want to add the action - when user click on the ImageSpan, it will popup a dialog and show the big image.

I checked the SDK and seems the ImageSpan doesn't support onclick. Is there anyway to enable the onclick for the ImageSpan or other Span that support Image?

I checked the code and found there is a URLSpan created with the ImageSpan because the input string is

But seems the URLSpan doesn't work and there is no click action create for it. Any idea?

Thanks.

like image 776
John Wu Avatar asked Apr 07 '11 02:04

John Wu


2 Answers

I've been trying to solve the same problem today and find the solution. To make the image clickable you need to attach a ClickableSpan object to the same range as ImageSpan for your image. When you get your Spanned object from Html.fromHtml() you can go through the set of ImageSpan objects assigned for it and attach additional ClickableSpan object.

Like this:

            ImageSpan[] image_spans = s.getSpans(0, s.length(), ImageSpan.class);

            for (ImageSpan span : image_spans) {

                final String image_src = span.getSource();
                final int start = s.getSpanStart(span);
                final int end = s.getSpanEnd(span);

                ClickableSpan click_span = new ClickableSpan() {

                    @Override
                    public void onClick(View widget) {

                        Toast.makeText(HtmlImagesTestActivity.this,
                                "Image Clicked " + image_src,
                                Toast.LENGTH_SHORT).show();

                    }

                };

                ClickableSpan[] click_spans = s.getSpans(start, end, ClickableSpan.class);

                if(click_spans.length != 0) {

                    // remove all click spans

                    for(ClickableSpan c_span : click_spans) {
                        s.removeSpan(c_span);
                    }


                }


                s.setSpan(click_span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            }               
like image 193
basv Avatar answered Sep 19 '22 19:09

basv


I have found the key point。 In order to response to click action, we not only set clickablespan , but also set edittext'setMovementMethod, the code is like this:

EditText.setMovementMethod(LinkMovementMethod.getInstance());

Here is the problem. If set setMovementMethod to LinkMovementMethod.getInstance(), the edittext's cursor will be gone. I don't know why

like image 26
miaohua1982 Avatar answered Sep 21 '22 19:09

miaohua1982