现在有一个需求:想要为TextView 设置drawableLeft能够跟随TextView的高度自动缩放。默认情况下drawableLeft 是大小不变化的
下面讲解怎么做的
首先我们要取得当前显示的TextView的大小,肯定不能再onCreate函数里面直接写
tv=(TextView)findViewById(R.id.tv);
//不能直接这么写
tv.getMeasureHeight();
因为在oncreate时TextView还没有展开
所以可以为TextView注册一个观察对象
ViewTreeObserver vto=lv.getViewTreeObserver();
//添加监听
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
}
});
然后在onGlobalLayout()函数中,就可以来动态的修改drawableLeft的大小
//取得当前高度
int h = tv.getMeasuredHeight();
//要显示的drawable
Drawable d = getResources().getDrawable(android.R.drawable.sym_def_app_icon);
//资源图片本身的大小
int inw = d.getIntrinsicWidth();
int inh = d.getIntrinsicHeight();
//通过tv的高度*资源宽高比计算宽度
int w = h * inw / inh;
//设置显示大小
d.setBounds(0, 0, w, h);
//为TextView添加drawableLeft(函数对应的参数是:drawableLeft,drawableTop,drawableRight,drawableBottom)
tv.setCompoundDrawables(d, null, null, null);
//取消监听
tv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
本文介绍如何让TextView左侧的图标能随着TextView高度的变化而自动调整大小。通过使用ViewTreeObserver监听全局布局事件,在TextView完全加载后获取其高度,并根据高度调整图标尺寸。

9481

被折叠的 条评论
为什么被折叠?



