Android(安卓)动态设置TextView的drawableLeft等属性
16lz
2021-12-04
之前在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设置的一样!
更多相关文章
- 箭头函数的基础使用
- NPM 和webpack 的基础使用
- Python list sort方法的具体使用
- 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程
- Kotlin编程之Kotlin Android(安卓)Extensions(扩展插件)
- Android访问网络,使用HttpURLConnection还是HttpClient?
- Android(安卓)UI开发第二十八篇――Fragment中使用左右滑动菜单
- android shape的使用
- Android——编译release版签名系统