欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android view getWidth 和 getHeight 的值为0

程序员文章站 2022-07-14 17:45:42
...

The getWidth and getHeight methods will return 0 if the view has not yet been inflated. For example, if you are trying to access it in the onCreate of the Activity, you'll get zero.

在UI 组件还未显示在界面之前调用getWidth和getHeight方法通常会得到0。所以不能在onCreate方法里获得组件的width和height.

可以通过以下两种方法获得:

float width=activity.getWindowManager().getDefaultDisplay().getWidth();
float height=activity.getWindowManager().getDefaultDisplay().getHeight();

或者重写onWindowFocusChanged,在这个方法里获取

public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		view.getHeight();
                view.getWidth();
	}


转载于:https://my.oschina.net/MrGuan/blog/61314