SpannableString简单的图文混排
SpannableString spannableString = new SpannableString("点击 按钮有惊喜");
ImageSpan imageSpan = new ImageSpan(this,R.mipmap.ic_launcher);
spannableString.setSpan(imageSpan,2,4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(spannableString);
Log.i("TextView",tv.getText().toString());
注意:在setSpan
方法中,start和end代表的是图片所占位置的开始和结尾。
在任意位置插入
int index = tv.getSelectionStart();
Editable edit = tv.getEditableText();
Drawable drawable = BitmapDrawable.createFromPath(resultList.get(0).getPhotoPath());
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
float ratio = (float)height/width;
deviceWidth = displayMetrics.widthPixels;
drawable.setBounds(0,0,deviceWidth, (int) (deviceWidth*ratio));
String str = "\n"+resultList.get(0).getPhotoPath()+"\n";
SpannableString spannableString = new SpannableString(str);
ImageSpan imageSpan = new ImageSpan(drawable, DynamicDrawableSpan.ALIGN_BASELINE);
spannableString.setSpan(imageSpan,1,str.length()-1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
if(index< 0 || index >=edit.length()){
edit.append(spannableString);
}else{
edit.insert(index+1,spannableString);
}
tv.setSelection(index+spannableString.length());
HTML方式实现图文混排
Html.ImageGetter getImageGetterInstance() {
Html.ImageGetter imgGetter = new Html.ImageGetter() {
@Override
public Drawable getDrawable(String source) {
int fontH = (int) (getResources().getDimension(
R.dimen.textSizeMedium) * 1.5);
int id = Integer.parseInt(source);
Drawable d = getResources().getDrawable(id);
int height = fontH;
int width = (int) ((float) d.getIntrinsicWidth() / (float) d
.getIntrinsicHeight()) * fontH;
if (width == 0) {
width = d.getIntrinsicWidth();
}
d.setBounds(0, 0, width, height);
return d;
}
};
return imgGetter;
}
主要依赖上面这个类,通过书写html代码来实现图文混排,使用img标签和src属性。tv.append(Html.fromHtml("<img src='"+resultList.get(0).getPhotoPath()+"'/>",getImageGetterInstance(),null));
同时注意,source就是在ImageSpan中的那个source。