在作facebook登陆时,正好看到其SDK中一段代码,能够根据屏幕像素适配本身的控件的大小,虽然本身之前也作过相似的逻辑,但不如人家的逻辑来的严谨,这里贴出来学习一下:
// width below which there are no extra margins
private static final int NO_PADDING_SCREEN_WIDTH = 480;
// width beyond which we're always using the MIN_SCALE_FACTOR
private static final int MAX_PADDING_SCREEN_WIDTH = 800;
// height below which there are no extra margins
private static final int NO_PADDING_SCREEN_HEIGHT = 800;
// height beyond which we're always using the MIN_SCALE_FACTOR
private static final int MAX_PADDING_SCREEN_HEIGHT = 1280;
private void calculateSize() {
WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
// always use the portrait dimensions to do the scaling calculations so we always get a portrait shaped
// web dialog
int width = metrics.widthPixels < metrics.heightPixels ? metrics.widthPixels : metrics.heightPixels;
int height = metrics.widthPixels < metrics.heightPixels ? metrics.heightPixels : metrics.widthPixels;
int dialogWidth = Math.min(
getScaledSize(width, metrics.density, NO_PADDING_SCREEN_WIDTH, MAX_PADDING_SCREEN_WIDTH),
metrics.widthPixels);
int dialogHeight = Math.min(
getScaledSize(height, metrics.density, NO_PADDING_SCREEN_HEIGHT, MAX_PADDING_SCREEN_HEIGHT),
metrics.heightPixels);
getWindow().setLayout(dialogWidth, dialogHeight);
}
// the minimum scaling factor for the web dialog (50% of screen size) private static final double MIN_SCALE_FACTOR = 0.5;/** * Returns a scaled size (either width or height) based on the parameters passed. * @param screenSize a pixel dimension of the screen (either width or height) * @param density density of the screen * @param noPaddingSize the size at which there's no padding for the dialog * @param maxPaddingSize the size at which to apply maximum padding for the dialog * @return a scaled size. */ private int getScaledSize(int screenSize, float density, int noPaddingSize, int maxPaddingSize) { int scaledSize = (int) ((float) screenSize / density); double scaleFactor; if (scaledSize <= noPaddingSize) { scaleFactor = 1.0; } else if (scaledSize >= maxPaddingSize) { scaleFactor = MIN_SCALE_FACTOR; } else { // between the noPadding and maxPadding widths, we take a linear reduction to go from 100% // of screen size down to MIN_SCALE_FACTOR scaleFactor = MIN_SCALE_FACTOR + ((double) (maxPaddingSize - scaledSize)) / ((double) (maxPaddingSize - noPaddingSize)) * (1.0 - MIN_SCALE_FACTOR); } return (int) (screenSize * scaleFactor); }