Android 动态设置TextView的drawableLeft等属性

之前在TextView文本的上下左右处添加一个图片时,都是直接在XML文件中配置如下:

android:drawableLeft="@drawable/icon_launcher"

android:drawablePadding="10dp"

现在需要在代码中动态地添加实现该功能,做法如下:

使用setCompoundDrawables(left, top, right, bottom);

或使用setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom),设置Drawable显示在text的左、上、右、下位置。

两者的区别:
setCompoundDrawables 画的drawable的宽高,是按drawable.setBound()设置的宽高,所以有The Drawables must already have had setBounds(Rect) called,即使用之前必须使用Drawable.setBounds设置Drawable的长宽。
而setCompoundDrawablesWithIntrinsicBounds画的drawable的宽高,是按drawable固定的宽高,所以才有The Drawables' bounds will be set to their intrinsic bounds.即通过getIntrinsicWidth()与getIntrinsicHeight()获得。故无需设置Drawables的bounds了。

TextView tv_title = (TextView) findViewById(R.id.tv_title);
tv_title.setText(R.string.main_function);

Drawable drawableLeft = getResources().getDrawable(R.drawable.icon_location);

//方法1:setCompoundDrawables 画的drawable的宽高,是按drawable.setBound()设置的宽高
drawableLeft.setBounds(0,0,drawableLeft.getMinimumWidth(),drawableLeft.getMinimumHeight());
//tv_title.setCompoundDrawables(drawableLeft, null, null, null);
 
//如果不需要右侧也添加图片,上面一行注释去掉结束即可
Drawable drawableRight = getResources().getDrawable(R.drawable.icon_arrow);
drawableRight.setBounds(0,0,drawableRight.getMinimumWidth(),drawableRight.getMinimumHeight());
tv_title.setCompoundDrawables(drawableLeft, null, drawableRight, null);
//设置间距
tv_title.setCompoundDrawablePadding(10);


//方法2:setCompoundDrawablesWithIntrinsicBounds画的drawable的宽高,是按drawable固定的宽高
//tv_title.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, null, null);
//tv_title.setCompoundDrawablePadding(10);

 效果和直接通过android:drawableLeft设置的一样!

你可能感兴趣的:(Android)