Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

android - How to add click action for the ImageSpan

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

            }               

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...