Search code examples
javaandroidkotlintextview

Vector drawable in any location within text view (not outside of it)


Is there a way to add a drawable in any position within a text view programmatically without having to position it on a particular side of a text view? The following code works when using unicode character but I want to try the same with a vector drawable.

textView.text = getString(R.string.app_settings) + " \u2794 " + getString(R.string.display)

enter image description here


Solution

  • For me, ImageSpan works. You can put a delimiter and replace it with the drawable. I used a google icon in this example

    Demo:

    Code with delimiter replacement:

        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.google_icon);
        drawable.setBounds(0, 0, 100,100);
    
        String text = " Google %google_icon% icon";
        String delimiter = "%google_icon%";
        
        int icon_index = text.indexOf("%google_icon%");
        text = text.replace(delimiter," ");
        
        Spannable span = new SpannableString(text);
        ImageSpan image = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
        span.setSpan(image, icon_index, icon_index+1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        
        textView.setText(span);
    

    Or, you can place the drawable on any index like:

    span.setSpan(image, start_index, end_index, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    

    PS: I used Display1 in text appearance. You need to change drawable bounds according to your own needs.