61

我正在寻找如何使用 ImageSpan 构建和显示 Android SpannableString 的示例。类似笑脸的内联显示。

非常感谢。

4

3 回答 3

123

找到以下内容,它似乎可以完成这项工作:

public class TestActivity extends Activity { 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    TextView textView  = (TextView) findViewById(R.id.textview); 
    SpannableString ss = new SpannableString("abc"); 
    Drawable d = ContextCompat.getDrawable(this, R.drawable.icon32);
    d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); 
    ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE); 
    ss.setSpan(span, 0, 3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); 
    textView.setText(ss); 
} 
于 2010-07-05T07:08:36.737 回答
20

SpannableString + ImageSpan 在 Android API 21 和 22 中不起作用(我在模拟器中的 Android Studio 1.2.1.1 中测试过),但如果你这样做:

TextView textView  = (TextView) findViewById(R.id.textview);
textView.setTransformationMethod(null);
...
textView.setText(ss); 

SpannableString + ImageSpan 将起作用。

我受到这篇文章的启发:https ://stackoverflow.com/a/26959656/3706042

于 2015-05-31T17:15:24.250 回答
0

如果有人仍然感兴趣,我创建了一个 Java 方法,允许基于“要替换的字符串”递归地将列出的可绘制对象添加到文本(设置在 textView 的末尾) 。

public void appendImages(@NonNull TextView textView,
                           @NonNull String text,
                           @NonNull String toReplace,
                           Drawable... drawables){
    if(drawables != null && drawables.length > 0){
        //list of matching positions, if any
        List<Integer> positions = new ArrayList<>();
        int index = text.indexOf(toReplace);
        while (index >= 0) {
            //add position
            positions.add(index);
            index = text.indexOf(toReplace, index + toReplace.length());
        }
        if(positions.size() > 0 && drawables.length >= positions.size()){
            textView.setTransformationMethod(null);
            SpannableString ss = new SpannableString(text);
            int drawablesIndex = 0;
            for(int position : positions){
                Drawable drawable = drawables[drawablesIndex++];
                //mandatory for Drawables
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                ss.setSpan(new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE), position, position+toReplace.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }
            textView.setText(ss);
        }
        else Timber.w("The amount of matches to replace is %s and the number of drawables to apply is %s", positions.size(), drawables.length);
    }
    else Timber.w("The drawables array is null or empty.");
}

用法:

appendImages(myTextView, "This is a ^ simple ^ test", "^", drawable1, drawable2);
于 2021-02-16T12:14:44.740 回答