li2
3/28/2016 - 3:12 AM

#

Add image to text in textView. 对于简单的图文混排的 TextView 可以使用 SpannableStringBuilder。

#tags: android-view

/*           __
Like this  (|__| represents an image):
 __              __
|__| Settings - |__| Safety.

Get TextView height by OnGlobalLayoutListener dynamically, and then
set drawable size by calling drawable.set(left, top, right, bottom),
in order to make sure the height of drawable is same as the string.

http://stackoverflow.com/questions/3591784/getwidth-and-getheight-of-view-returns-0
http://stackoverflow.com/questions/8953379/android-add-image-to-text-in-text-view

必须动态的获取 TextView 高度,然后调用 drawable.set(left, top, right, bottom) 设置其大小,
否则 drawable 和 string 高度不一致,难看。
*/

mTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        int height = mEntryTextView.getHeight();
        buildEntryString(height);
        mTextView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    }
});

private void buildEntryString(int height) {
    String str1 = getString(R.string.action_title_settings) + " - ";
    String str2 = getString(R.string.action_title_safety) + ".";

    SpannableStringBuilder span1 = addImageToText(getActivity(), R.drawable.ic_settings, str1, height);
    SpannableStringBuilder span2 = addImageToText(getActivity(), R.drawable.ic_safety, str2, height);
    mTextView.setText(TextUtils.concat(span1, span2));
}

private SpannableStringBuilder addImageToText(Context context, int drawableId, String text, int height) {
    Drawable drawable = ContextCompat.getDrawable(context, drawableId);
    int width = height * drawable.getIntrinsicWidth() / drawable.getIntrinsicHeight();
    drawable.setBounds(0, 0, width, height);

    SpannableStringBuilder ssb = new SpannableStringBuilder(" " + text);
    ssb.setSpan(new ImageSpan(drawable), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    return ssb;
}