继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

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

ABOUTYOU
关注TA
已关注
手记 300
粉丝 67
获赞 358

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

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP