我们知道,TextView控件一般是用来显示文本的,而图片一般是用ImageView控件来显示。
那TextView能否显示图片呢?答案是肯定的!下面列出常见的4种方式。
#XML文件中指定属性值
这种方式应该是最常用的了,在TextView的左上右下显示图片,可用
android:drawableLeft
android:drawableTop
android:drawableRight
android:drawableBottom
比如我们要在TextView的顶部设置图片,代码如下:
<TextView
android:id="@+id/textview_01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="@drawable/ic_launcher"
android:text="hello_world" />
这种显示方式图片跟文本是居中对齐的,此种方式对应的方法是setCompoundDrawablesWithIntrinsicBounds:
mTextView01.setCompoundDrawablesWithIntrinsicBounds(null,
getResources().getDrawable(R.drawable.ic_launcher, null), null, null);
效果图:

如果觉得图片离文字太近,也可以设置他们之间的间距,xml或者代码中都可以实现:
android:drawablePadding="10dp"
或者
mTextView01.setCompoundDrawablePadding(10);
#通过解析HTML来显示图片
这种方式可以显示项目中的图片、本地SDCARD和网络的图片,当然网络的图片必须先下载到本地然后显示。
##显示项目中图片
看代码
// 第二种方式:显示项目中的图片
mTextView02 = (TextView) findViewById(R.id.textview_02);
// 把图片生成的ID加入img标签中 <img src='123'>
Strin

本文介绍了在Android中TextView显示图片的4种方法:通过XML属性设置,解析HTML,使用ImageSpan,以及自定义绘制。详细讲解了每种方法的实现步骤及效果,包括设置图片与文本间距、从资源、本地、网络加载图片等。
最低0.47元/天 解锁文章
3321

被折叠的 条评论
为什么被折叠?



