Search code examples
androidtextviewspannablestringspannablestringbuilderimagespan

Android : Adding an imageview right at the end of a textview via ImageSpan and make the image clickable


enter image description here

I want to achieve a design as shown above in the screenshot. The image is fetched from a URL and I want to add a click listener in the image only. Tried using Image span but with no success. Could somebody help me through this?

Thank you


Solution

  • Here is a more complete answer to your question. I use a drawable resource, but you can create a drawable from your bitmap. See the following code for a description. This code can be placed into the onCreate() of your main activity (or elsewhere.)

    enter image description here

    // Get a string that can be spanned with an ImageSpan and a ClickableSpan.
    SpannableString ss = new SpannableString("Some text ");
    // This will be the image. I use a resource here, but there are constructors that can
    // accept a Drawable. See BitmapDrawable at https://developer.android.com/reference/android/graphics/drawable/BitmapDrawable#BitmapDrawable(android.content.res.Resources,%20android.graphics.Bitmap)
    
    ImageSpan imgSpan = new ImageSpan(this, R.drawable.ic_baseline_airplanemode_active_24, ImageSpan.ALIGN_CENTER);
    ClickableSpan cs = new ClickableSpan() {
        @Override
        public void onClick(@NonNull View widget) {
            Toast.makeText(MainActivity.this, "Clicked!", Toast.LENGTH_SHORT).show();
        }
    };
    
    // The image will overlay the last blank in the text.
    ss.setSpan(imgSpan, ss.length() - 1, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    // The clickable span will overlay the image from the ImageSpan.
    ss.setSpan(cs, ss.length() - 1, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    // Just a TextView.
    TextView myView = findViewById(R.id.myView);
    myView.setText(ss);
    // Prevent the ImageSpan from showing a highlight on click.
    myView.setHighlightColor(getResources().getColor(android.R.color.transparent));
    // Make sure the TextView can be clicked.
    myView.setMovementMethod(LinkMovementMethod.getInstance());