TextView动态设置图片

本文介绍在Android开发中,如何使用TextView控件显示图片。通过XML属性设置和代码动态设置两种方式,详细解释了如何在文本视图的上下左右位置添加图片,并调整间距。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

TextView控件一般是用来显示文本的,而图片一般是用ImageView控件来显示,现在直接用textview来设置图片。

1.XML属性设置

最常见的一种方式,在控件的上下左右设置,可用
android:drawableLeft
android:drawableTop
android:drawableRight
android:drawableBottom

<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" />
    
    设置间距 android:drawablePadding="8dp"
2.代码动态设置

①可用setCompoundDrawables(null,null,null,null)

 drawable = getResources().getDrawable(R.mipmap.launcher);
 drawable.setBounds(0, 0, drawable.getMinimumWidth(),drawable.getMinimumHeight());  // 必须要设置
 textView.setCompoundDrawables(drawable, null, null, null); //括号里面的四个参数代表左上右下四个方向的图片,可以同时设置多个

②用setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);

drawable = getResources().getDrawable(R.mipmap.launcher);
textView.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null);
textView.setCompoundDrawablePadding(5); // 设置间距

此方法就是把setCompoundDrawables在封装,内部实际就是调用setCompoundDrawables方法。不想设置图片,把四个参数都设置为null。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值