背景图片拉伸,计算屏幕宽度和获取控件宽高
背景图片拉伸: 那么如果我们想在Activity的onCreate方法或者是onReusme方法获取组件的宽高怎么办呢?这里提供了以下的五种方式:http://blog.csdn.net/qq_23547831/article/details/51764304 1、重写Activity的onWindowFocusChanged方法 /** * 重写Acitivty的onWindowFocusChanged方法 */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); /** * 当hasFocus为true的时候,说明Activity的Window对象已经获取焦点,进而Activity界面已经加载绘制完成 */ if (hasFocus) { int widht = titleText.getWidth(); int height = titleText.getHeight(); Log.i(TAG, "onWindowFocusChanged width:" + widht + " " + " height:" + height; } } 说明: 这样重写onWindowFocusChanged方法,当获取焦点的时候我们就可以通过getWidth和getHeight方法得到组件的宽和高了。但是这时候这个方法的逻辑可能会执行多次,也就是说只要我们的Activity的window对象获取了焦点就会执行该语句, 所以我们需要做一些逻辑判断,让它在我们需要打印获取组件宽高的时候在执行。 example: @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if(hasFocus){ mLayoutWidth = mBackgroundImg.getWidth(); } setPic(); } private void setPic() { ViewGroup.LayoutParams lp = mBackgroundImg.getLayoutParams(); int screenWidth = VAUtils.getScreenWidth(this);//屏幕宽度(像素) int screenHeight = VAUtils.getScreenHeight(this); lp.width = screenHeight > screenWidth ? mLayoutWidth : (int) (screenHeight * 0.5); lp.height = (int) (lp.width * 0.673); mBackgroundImg.setLayoutParams(lp); } 2、获取屏幕宽高(1600X2454)SHT,VAUtils: public static int getScreenHeight(Context context) {//获取屏幕高度 WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); Point point = new Point(); display.getSize(point); return point.y; } public static int getScreenWidth(Context context) {//获取屏幕宽度 WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); Point point = new Point(); display.getSize(point); return point.x; } 3、判断屏幕尺寸(英寸) public static boolean isTablet() { WindowManager wm = (WindowManager) VAssistantConfig.getAppContext().getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); DisplayMetrics dm = new DisplayMetrics(); display.getMetrics(dm); double x = Math.pow(dm.widthPixels / dm.xdpi, 2);//dm.widthPixels:屏幕宽度(像素px),dm.xdpi:每一寸的屏幕密度(DPI(Dots Per Inch,每英寸点数)是一个量度单位,用于点阵数码影像) double y = Math.pow(dm.heightPixels / dm.ydpi, 2); double screenInches = Math.sqrt(x + y); if (screenInches >= 8.0) { return true; } return false; }