項目中經常要用到屏幕分辨率來計算控件尺寸來適應不同的屏幕,所以寫一下記錄下
直接上佈局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/af"
android:orientation="vertical" >
<TextView
android:id="@+id/id_txt_hello"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textColor="#fff" />
<TextView
android:id="@+id/id_txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/hah"
android:text="@string/hello"
android:textColor="#000" />
</LinearLayout>
直接上代碼:
public class GetStatusBarHeightDemoActivity extends Activity {
private Window window_;
/**當前界面根view*/
private View view_boot_;
private TextView txt_hello_;
private TextView txt_;
/**屏幕寬度*/
private int screenWidth_;
/**屏幕高度*/
private int screenHeight_;
/**狀態欄高度*/
private int statusBarHeight_;
/**標題欄高度*/
private int titleBarHeight_;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_get_status_and_title_height);
txt_hello_ = (TextView)findViewById(R.id.id_txt_hello);
txt_ = (TextView)findViewById(R.id.id_txt);
Display display = getWindowManager().getDefaultDisplay();
screenWidth_ = display.getWidth();
screenHeight_ = display.getHeight();
window_ = getWindow();
/*取得系統當前顯示的 view根(它是一個framelayout對象)*/
view_boot_ = window_.findViewById(Window.ID_ANDROID_CONTENT);
txt_hello_.post(new Runnable() {
public void run() {
/*獲取相關參數*/
getRelatedAttributeValue();
}
});
}
/**
* 獲取相關屬性值
*/
private void getRelatedAttributeValue(){
/*定義一個區域*/
Rect frame = new Rect();
/*區域範圍爲該textview的區域範圍*/
txt_hello_.getWindowVisibleDisplayFrame(frame);
/*獲取狀態欄高度。因爲獲取的區域不包含狀態欄*/
statusBarHeight_ = frame.top;
/*獲取除了狀態欄和標題內容的起始y座標,也就是 狀態欄+標題欄的高度*/
int contentTop = view_boot_.getTop();
/*一減得出標題欄高度*/
titleBarHeight_ = contentTop - statusBarHeight_;
txt_.setText("屏幕寬度=" + screenWidth_
+ "\n屏幕高度=" + screenHeight_
+ "\n狀態欄高度=" + statusBarHeight_
+ "\n標題欄高度=" + titleBarHeight_);
}
}
如果感覺這個方法獲取到0,還可以參照網上的一個辦法,用反射來獲取:
Class<?> c = null;
Object obj = null;
Field field = null;
int x = 0, sbar = 0;
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();
}
這個辦法在自定義控件裏也很好用。
源代碼: