且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android 获取View宽度

更新时间:2022-08-12 20:20:54

/*****************************************************************************
 *                         Android 获取View宽度
 * 说明:
 *     在View默认的构造函数里无法获取到View的宽高,需要采用另外的方式获取。
 *
 *                                           2016-6-15 深圳 南山平山村 曽剑锋
 ****************************************************************************/

一、参考文档:
    If I call getMeasuredWidth() or getWidth() for layout in onResume they return 0
        http://***.com/questions/6939002/if-i-call-getmeasuredwidth-or-getwidth-for-layout-in-onresume-they-return-0

二、解决办法:
    this.post(new Runnable() {
         public void run() {
             centerX = getMeasuredWidth()/2;
             centerY = getMeasuredHeight()/2;
             ball = new Ball(centerX, centerY);
         }
    }
    );