這個問題並不複雜,但是問的人實在很多,所以還是集中回答一下。
從Android 3.2(API Level 13)開始,在Activity裡使用下面的方法來擷取螢幕尺寸(單位是像素):
Display display = getWindowManager().getDefaultDisplay(); //Activity#getWindowManager()Point size = new Point();display.getSize(size);int width = size.x;int height = size.y;
如果代碼不是寫在Activity裡,用下面的方法(通過WINDOW_SERVICE擷取display對象):
WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);Display display = wm.getDefaultDisplay();display.getSize(size);int width = size.x;int height = size.y;
如果Android版本小於3.2,那麼因為Display對象還沒有getSize()方法,應該用下面的方法擷取螢幕尺寸:
Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight();
最後,附Android系統版本與API Level對照表:
Platform Version |
API Level |
VERSION_CODE |
Notes |
Android 4.2 |
17 |
JELLY_BEAN_MR1 |
|
Android 4.1, 4.1.1 |
16 |
JELLY_BEAN |
Platform Highlights |
Android 4.0.3, 4.0.4 |
15 |
ICE_CREAM_SANDWICH_MR1 |
Platform Highlights |
Android 4.0, 4.0.1, 4.0.2 |
14 |
ICE_CREAM_SANDWICH |
Android 3.2 |
13 |
HONEYCOMB_MR2 |
|
Android 3.1.x |
12 |
HONEYCOMB_MR1 |
Platform Highlights |
Android 3.0.x |
11 |
HONEYCOMB |
Platform Highlights |
Android 2.3.4 Android 2.3.3 |
10 |
GINGERBREAD_MR1 |
Platform Highlights |
Android 2.3.2 Android 2.3.1 Android 2.3 |
9 |
GINGERBREAD |
Android 2.2.x |
8 |
FROYO |
Platform Highlights |
Android 2.1.x |
7 |
ECLAIR_MR1 |
Platform Highlights |
Android 2.0.1 |
6 |
ECLAIR_0_1 |
Android 2.0 |
5 |
ECLAIR |
Android 1.6 |
4 |
DONUT |
Platform Highlights |
Android 1.5 |
3 |
CUPCAKE |
Platform Highlights |
Android 1.1 |
2 |
BASE_1_1 |
|
Android 1.0 |
1 |
BASE |
|
參考資料
Display | Android Developers
Android: How to get screen dimensions
What is API Level?