Android 动态设置TextView的drawableLeft等属性
16lz
2021-01-23
之前在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学习方法路线
- Android横竖屏切换方法
- 在deepin系统中adb操作android文件的方法
- 常用的Js调Android方法,以及Android原生传值给Js
- 集成第三方库到android程序方法
- Android——《Android第一行代码》中使用通知 方法,Android8.0系
- 在Android Stduio 中使用requestWindowFeature(Window.FEATURE_N
- Android禁止横竖屏和解决切换屏幕时重启Activity的方法