开发过程中,用到了一个自定义的View,而在View的内容数据没有被加载进来时,我想要先绘制这个View的背景,于是在使用到:
Rect bgRect = new Rect(report_ecg_wave.getLeft(), report_ecg_wave.getTop(), report_ecg_wave.getWidth(),
report_ecg_wave.getHeight());
report_ecg_wave.setBgRect(bgRect);
report_ecg_wave.initParams();
report_ecg_wave.drawBitmap();
时报错:java.lang.IllegalArgumentException: width and height must be > 0
后来了解到在onCreate()时获取view的width和height时,由于view还没有被绘制到界面上,此时获取不到view的width和height。晚上查看了一些其他童鞋的解决方案,有重写onWindowsFocuschanged的,也有其他的,感觉有些麻烦。所以就想到用另起线程执行的方式,这样可以在UI线程执行完成之后,才执行该子线程,此时就可以得到view的width以及height了,而且很简单的两行代码:
report_ecg_wave.post(new Runnable() {
@Override
public void run() {
drawWaveBg();
}
});