之前在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设置的一样!

更多相关文章

  1. Android学习方法路线
  2. Android横竖屏切换方法
  3. 在deepin系统中adb操作android文件的方法
  4. 常用的Js调Android方法,以及Android原生传值给Js
  5. 集成第三方库到android程序方法
  6. Android——《Android第一行代码》中使用通知 方法,Android8.0系
  7. 在Android Stduio 中使用requestWindowFeature(Window.FEATURE_N
  8. Android禁止横竖屏和解决切换屏幕时重启Activity的方法

随机推荐

  1. Android(安卓)ZXing 二维码、条形码扫描
  2. Android(安卓)打造炫目的圆形菜单 秒秒钟
  3. Android窗口管理服务WindowManagerServic
  4. 为Android、iOS设备搭建模拟丢包、慢速网
  5. [Xamarin.Android] 如何透過電子郵件部署
  6. 初始化一个构建环境
  7. 本人初学android,希望大神帮忙指点学习路
  8. 15个必知的Android开发者选项
  9. 【Android】Java回调原理并结合Android源
  10. Android:探究活动的生命周期