Sometimes you may want to add some images to TextView. For example, when you input a contact via text message, you need to change the contact number to an image. However, you cannot use a fixed image, it is customized based on the content, which is more like a view.
ClickableImageSpan
At the same time, we found that the LinkMovementMethod provided by google only executes the onClick () method of ClickableSpan. below is the source code of the onTouchEvent () of LinkMovementMethod. This method responds when we click Spanned.
action = (action == MotionEvent.ACTION_UP ||== x = ( y = (-=-=+=+== line = off = (link.length != 0 (action == } (action ==00
This method is actually used to find the corresponding Span through coordinates. Then, when the link array is not empty, the span is obtained and its onClick () method is executed. Here we have noticed this code.
ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.);
This indicates that this method only obtains ClickableSpan, because if we directly use the system LinkMovementMethod class, ImageSpan cannot respond to the click event .. As we know, ImageSpan does not inherit ClickableSpan. Therefore, the author writes a ClickableMovementMethod
ClickableMovementMethod (sInstance == = action = (action == MotionEvent.ACTION_UP ||== x = ( y = (-=-=+=+== line = off == buffer.getSpans(off, off, ClickableSpan. (link.length != 0 (action ==0 (action ==00
This class supports both ClickableSpan and ClickableImageSpan.
So far, a clickable ImageSpan is complete. The remaining steps are the same as the method for implementing text styles. For specific code implementation, refer to the text style over there and make a slight modification. The specific author no longer posts this part of code.
So what should we do if we need to display a custom View instead of passing a simple image. In fact, you only need to convert the View to Drawable. The following is the main implementation code:
= LayoutInflater.from(ctx).inflate(R.layout.viewt, spec = View.MeasureSpec.makeMeasureSpec(00, 0== -view.getScrollX(), -== cacheBmp.copy(Bitmap.Config.ARGB_8888, = createDrawble(tv.getContext(), sp.toString);0, 0=
The createDrawble () method converts a View to A BItmap Using the getDrawingCache () method of the View. After obtaining the BitmapDrawable, do not forget to call setBounds (). This method determines the image size, if you do not set the image size, you can adjust the image size in this way if the image size is too large or too small. Other steps I believe you have read the author's parsing the URL in TextView and other designated special strings and click events, so there should be no difficulty in implementation. Therefore, I will not go into details.
If you have any questions or better insights, you can leave a message and learn from each other!