在给TextView设置图标的时候,在xml文件里用

android:drawableStart="@drawable/icon"设置TextView图标,

发现UI给的图标太大,太难看

但是在xml布局文件里无法修改图标大小,让UI重新弄图标又太麻烦

于是上网找看有没有可以修改大小的方法

最后发现在代码里动态设置TextView图标的两个方法

setCompoundDrawables(@Nullable Drawable left,@Nullable Drawable top,@Nullable Drawable right,@Nullable Drawable bottom)

以及

setCompoundDrawablesWithIntrinsicBounds(@DrawableRes intleft,@DrawableRes inttop,@DrawableRes intright,@DrawableRes intbottom)

两者的区别是,前者设置Drawable前,要通过Drawable.setBounds设置Drawable的长宽,后者不用。

所以我们可以在setBounds()时将图标设置成我们想要的大小

以下是实现代码

Drawable icon = getResources().getDrawable(R.drawable.icon);

//setBounds(left,top,right,bottom)里的参数从左到右分别是

//drawable的左边到textview左边缘+padding的距离,drawable的上边离textview上边缘+padding的距离

//drawable的右边边离textview左边缘+padding的距离,drawable的下边离textview上边缘+padding的距离

//所以right-left = drawable的宽,top - bottom = drawable的高

icon.setBounds(0,0,40,44);

mTextView.setCompoundDrawables(icon, null, null, null);

关于TextView的各种间距,如下图所示

b17f8a58673b52b3ff41dcef325757a6.png

图片来自 http://www.jianshu.com/p/fd9cce7a333f

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐