首先,有一点需要声明,其实在android中,画布Canvas的高宽其实是屏幕的高宽。
如此一来,获得屏幕高宽的方法就很多了:
1.
- WindowManager windowManager = getWindowManager();
- Display display = windowManager.getDefaultDisplay();
- screenWidth = display.getWidth();
- screenHeight = display.getHeight();
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
screenWidth = display.getWidth();
screenHeight = display.getHeight();
2.
- DisplayMetrics dm = new DisplayMetrics();
- this.getWindowManager().getDefaultDisplay().getMetrics(dm);//this指当前activity
- screenWidth =dm.widthPixels;
- screenHeight =dm.heightPixels;
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(dm);//this指当前activity
screenWidth =dm.widthPixels;
screenHeight =dm.heightPixels;
以上两种方法在屏幕未显示的时候,还是处于0的状态,即要在setContentView调用之后才有效。
3.
还可以在onDraw中由canvas来获得
- screenWidth =canvas.getWidth();
- screenHeight =canvas.getHeight();
screenWidth =canvas.getWidth();
screenHeight =canvas.getHeight();
而视图的高宽则是大多数人所认为的canvas的高宽,其实他所指的是除了任务栏和状态栏的高宽,主要有如下方法:
1.
- viewWidth=this.getWidth();
- viewHeight=this.getHeight();
viewWidth=this.getWidth();
viewHeight=this.getHeight();
2.重写view的onSizeChanged,该方法会在onCreate之后,onDraw之前调用
- protected void onSizeChanged(int w, int h, int oldw, int oldh) {
- viewHeight=h;
- viewWidth=w;
- super.onSizeChanged(w, h, oldw, oldh);
- }
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
viewHeight=h;
viewWidth=w;
super.onSizeChanged(w, h, oldw, oldh);
}
任务栏、状态栏的高宽的高宽我目前还不清楚,不过从网上查找可知:
引用
frameworks/core/res/values/themes.xml
<item name="windowTitleSize">25dip</item>
frameworks/core/res/values/dimens.xml
<dimen name="status_bar_height">25dip</dimen>
<item name="windowTitleSize">25dip</item>
frameworks/core/res/values/dimens.xml
<dimen name="status_bar_height">25dip</dimen>
在一个activity中如果要获取高宽,最好是放在onSizeChanged中比较保险。
以上是我对android获得高宽的一点总结,如果有错误的地方,欢迎留言探讨。
另外,还有对屏幕显示的一些设置:
//设置为无标题
- requestWindowFeature(Window.FEATURE_NO_TITLE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
//设置为全屏模式getWindow().setFlags
- getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
//设置为横屏
- setRequesteOrientation(ActivityInfo.SCREEN_ORIENTATION_LADSCAPE);