您的位置:首页 > 其它

获取屏幕分辨率以及状态栏标题栏高度最简洁的办法

2012-06-29 17:26 405 查看
项目中经常要用到屏幕分辨率来计算控件尺寸来适应不同的屏幕,所以写一下记录下



直接上布局:

<?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();
}


这个办法在自定义控件里也很好用。

源代码:

http://download.csdn.net/detail/zoeice/4401559
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: