安卓java 代码中动态实现 TextView的 DrawableTop属性

来源:互联网 发布:经典球员数据盖德穆勒 编辑:程序博客网 时间:2024/05/28 15:21
 
标签: androidxmldrawabletextviewruntime
 5391人阅读 评论(0) 收藏 举报
 分类:

开发中我们想实现一种带图标的 TextView的时候 一般会使用 TextView的drawableTop,drawableLeft,等 属性,这个属性是在xml文件中定义的。

 <TextView            android:id="@+id/tv_homapage"            android:paddingTop="10dp"            android:drawableTop="@mipmap/ico_home_normal"            android:textColor="@color/white"            android:gravity="center"            android:text="首页"            android:layout_weight="1"            android:layout_width="0dp"            android:layout_height="match_parent" />
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

但是有时候我们想在Java代码中动态的修改 drawable的值,也就是在运行时 修改 drawable的状态。

这个时候我们可以使用如下方法

Drawable top = getResources().getDrawable(R.drawable.image);button.setCompoundDrawablesWithIntrinsicBounds(null, top , null, null);
  • 1
  • 2
  • 1
  • 2

我们动态的获取drawable资源,然后设置给button或者 TextView,

button.setCompoundDrawablesWithIntrinsicBounds(null, top , null, null);
  • 1
  • 1

这个方法的四个参数分别是指,left ,top,right ,bottom。 也就是你要添加的 drawable图片相对于text的位置。

如果不想在某个位置添加图片则设置为null即可。

reference link

阅读全文
0 0
原创粉丝点击