开发中我们想实现一种带图标的 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" />
但是有时候我们想在java代码中动态的修改 drawable的值,也就是在运行时 修改 drawable的状态。
这个时候我们可以使用如下方法
Drawable top = getResources().getDrawable(R.drawable.image);
button.setCompoundDrawablesWithIntrinsicBounds(null, top , null, null);
我们动态的获取drawable资源,然后设置给button或者 TextView,
button.setCompoundDrawablesWithIntrinsicBounds(null, top , null, null);
这个方法的四个参数分别是指,left ,top,right ,bottom。 也就是你要添加的 drawable图片相对于text的位置。
如果不想在某个位置添加图片则设置为null即可。