搜索
您的当前位置:首页正文

Android:使用SpannableString实现图片替换相

来源:二三娱乐

google官网地址:

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

最近项目中有个需求,图片和文字一块排版,最多显示两行,最开始想到的就是在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是后台返回的要显示的字符串,前面的空格是要用图片替代的地方,最终效果图如下:

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

Top