为了账号安全,请及时绑定邮箱和手机立即绑定

Android:使用SpannableString实现图片替换相应的文字

标签:
Android

google官网地址:

https://developer.android.com/reference/android/text/SpannableString.html

This is the class for text whose content is immutable but to which markup objects can be attached and detached. 

For mutable text, see SpannableStringBuilder.

这类文本的内容是不变的,但标记对象可以被附加和分离。如果目标是可变文本,看SpannableStringBuilder

最近项目中有个需求,图片和文字一块排版,最多显示两行,最开始想到的就是在TextView里面设置android:drawableLeft="@mipmap/tonbaopay_icon"显示图片并用android:drawablePadding="10dp"来控制图片和文字之间的距离,附XML代码:

<TextView

android:id="@+id/tv_goodscar_title"

android:layout_width="wrap_content"

android:layout_height="wrap_content"


android:drawableLeft="@mipmap/tonbaopay_icon"

android:drawablePadding="10dp"

android:layout_marginLeft="13dp"

android:layout_marginRight="15dp"

android:layout_toRightOf="@id/iv_goodscar_img"

android:maxLines="2"

android:paddingTop="7dp"

android:text="title"

android:textColor="#333333"

android:textSize="14sp"/>

然而效果是这样的:

图片被当成整体排在了左边,跟需求是不一样的!下面用SpannableString来实现一下,

XML代码:

<TextView

android:id="@+id/tv_goodscar_title"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="13dp"

android:layout_marginRight="15dp"

android:layout_toRightOf="@id/iv_goodscar_img"

android:maxLines="2"

android:paddingTop="7dp"

android:text="title"

android:textColor="#333333"

android:textSize="14sp"/>

在代码中写:

SpannableString msp =newSpannableString("  "+ goodsCart.goods.name);

Drawable rightDrawable =getResources().

getDrawable(R.mipmap.tonbaopay_icon);

rightDrawable.setBounds(0,0,

rightDrawable.getIntrinsicWidth(), rightDrawable.getIntrinsicHeight());

msp.setSpan(new ImageSpan(rightDrawable),0,1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

cellHolder.tv_goodscar_title.setText(msp);

其中goodsCart.goods.name是后台返回的要显示的字符串,前面的空格是要用图片替代的地方,最终效果图如下:


     跟需求是一样的,嗯,就到这里吧。

             

github地址:https://github.com/crazyqiang



作者:_小马快跑_
链接:https://www.jianshu.com/p/8b92f94efe25

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消