之前在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. 箭头函数的基础使用
  2. NPM 和webpack 的基础使用
  3. Python list sort方法的具体使用
  4. 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程
  5. Kotlin编程之Kotlin Android(安卓)Extensions(扩展插件)
  6. Android访问网络,使用HttpURLConnection还是HttpClient?
  7. Android(安卓)UI开发第二十八篇――Fragment中使用左右滑动菜单
  8. android shape的使用
  9. Android——编译release版签名系统

随机推荐

  1. Android的无边界程序设计理念
  2. android 电池(三):android电池系统
  3. 史上最全的Android开发学习教程集锦【初
  4. Android(安卓)应用程序主框架搭建
  5. Android:使用jsoup解析网页
  6. Android(安卓)SDCard Mount 流程分析(一)
  7. Android启动过程以及各个镜像的关系——
  8. Android(安卓)sp 指针类的用法
  9. 如何消除原生Android网络状态上的惊叹号
  10. Android设计规范