get a String of which with a Drawable in front via SpannableStringBuilder - Android Graphics

Android examples for Graphics:Drawable

Description

get a String of which with a Drawable in front via SpannableStringBuilder

Demo Code


//package com.java2s;

import android.graphics.drawable.Drawable;

import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.DynamicDrawableSpan;

public class Main {
    /**//from ww w.  ja  va  2  s  .c  o m
     * get a String of which with a Drawable in front.
     *
     * @param textSize the size of text
     * @param text the content of text
     * @param drawable the drawable you want to put in front of text
     * @return String with drawable
     */
    public static CharSequence getDrawableTextSpan(final int textSize,
            String text, final Drawable drawable) {
        SpannableStringBuilder sb = new SpannableStringBuilder(" ");
        sb.append(text);
        DynamicDrawableSpan drawableSpan = new DynamicDrawableSpan() {
            @Override
            public Drawable getDrawable() {
                float height = textSize;
                float width = drawable.getIntrinsicWidth() * height
                        / drawable.getIntrinsicHeight();
                drawable.setBounds(0, 0, (int) width, (int) height);
                return drawable;
            }
        };
        sb.setSpan(drawableSpan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        return sb;
    }
}

Related Tutorials