首页 > 代码库 > android TextView里边实现图文混配效果
android TextView里边实现图文混配效果
用TextView实现这种效果,图片文字混排,文字不同颜色字体。打电话和吊起浏览器等等
代码例如以下:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTextView = (TextView) this.findViewById(R.id.img_iv);
//创建一个 SpannableString对象
SpannableString sp = new SpannableString("这句话中有百度超链接,有高亮显示,这样,或者这样,还有斜体.");
//设置超链接
sp.setSpan(new URLSpan("http://www.baidu.com"), 5, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//设置高亮样式一
sp.setSpan(new BackgroundColorSpan(Color.RED), 17 ,19,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//设置高亮样式二 sp.setSpan(new ForegroundColorSpan(Color.YELLOW),20,24,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
//设置斜体
sp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 27, 29, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
//打电话
sp.setSpan(new URLSpan("tel:4155551212"), 2, 5,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//图片显示在textview里边
Drawable d = getResources().getDrawable(R.drawable.ic_launcher);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
sp.setSpan(span, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
//SpannableString对象设置给TextView
myTextView.setText(sp);
//设置TextView可点击
myTextView.setMovementMethod(LinkMovementMethod.getInstance());
}
android TextView里边实现图文混配效果