Android TextView设置图标,调整图标大小

来源:互联网 发布:全国省市区街道数据库 编辑:程序博客网 时间:2024/05/01 15:26

在给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 int left,        @DrawableRes int top, @DrawableRes int right, @DrawableRes int bottom)

两者的区别是,前者设置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的各种间距,如下图所示


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

原创粉丝点击