獲取狀態欄高度
一、傳統方式:有時獲取為0,解決方法看 二
|
代碼
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
|
二、4.0.3之后可能獲取為0
|
public int getBarHeight(){
Class<?> c = null;
Object obj = null;
Field field = null;
int x = 0, sbar = 38;//默認為38,貌似大部分是這樣的
try {
c = Class.forName("com.android.internal.R$dimen");
obj = c.newInstance();
field = c.getField("status_bar_height");
x = Integer.parseInt(field.get(obj).toString());
sbar = getResources().getDimensionPixelSize(x);
} catch (Exception e1) {
e1.printStackTrace();
}
return sbar;
}
|
//---------------------------------------------
1.獲取狀態欄高度:
decorView是window中的最頂層view,可以從window中獲取到decorView,然后decorView有個getWindowVisibleDisplayFrame方法可以獲取到程序顯示的區域,包括標題欄,但不包括狀態欄。
於是,我們就可以算出狀態欄的高度了。
|
代碼
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
|
有時候獲取到的高度是0,可以用另一種方法獲取
在源碼程序中獲取狀態欄高度代碼:
height= getResources().getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);
|
代碼
class c = Class.forName("com.android.internal.R$dimen");
Object obj = c.newInstance();
Field field = c.getField("status_bar_height");
int x = Integer.parseInt(field.get(obj).toString());
int y = getResources().getDimensionPixelSize(x);
|
2.獲取標題欄高度:
getWindow().findViewById(Window.ID_ANDROID_CONTENT)這個方法獲取到的view就是程序不包括標題欄的部分,然后就可以知道標題欄的高度了。
|
代碼
int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
//statusBarHeight是上面所求的狀態欄的高度
int titleBarHeight = contentTop - statusBarHeight
|
3.獲取屏幕高度
方法 1.
Java代碼
|
代碼
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
screenWidth = display.getWidth();
screenHeight = display.getHeight();
|
方法 2.
|
Java代碼
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(dm);//this指當前activity
screenWidth =dm.widthPixels;
screenHeight =dm.heightPixels;
|
以上兩種方法在屏幕未顯示的時候,還是處於0的狀態,即要在setContentView調用之后才有效。
設置為無標題
requestWindowFeature(Window.FEATURE_NO_TITLE);
設置為全屏模式getWindow().setFlags
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
設置為橫屏
setRequesteOrientation(ActivityInfo.SCREEN_ORIENTATION_LADSCAPE);