如何获取屏幕宽度和高度并将此值用于:
@Override protected void onMeasure(int widthSpecId, int heightSpecId) { Log.e(TAG, "onMeasure" + widthSpecId); setMeasuredDimension(SCREEN_WIDTH, SCREEN_HEIGHT - game.findViewById(R.id.flag).getHeight()); }
使用此代码,您可以获得运行时显示的宽度和高度:
DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); int height = displayMetrics.heightPixels; int width = displayMetrics.widthPixels;
在视图中,您需要执行以下操作:
((Activity) getContext()).getWindowManager() .getDefaultDisplay() .getMetrics(displayMetrics);
在某些情况下,设备有导航栏,您必须在运行时检查:
public boolean showNavigationBar(Resources resources) { int id = resources.getIdentifier("config_showNavigationBar", "bool", "android"); return id > 0 && resources.getBoolean(id); }
如果设备有导航栏,则计算其高度:
private int getNavigationBarHeight() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); int usableHeight = metrics.heightPixels; getWindowManager().getDefaultDisplay().getRealMetrics(metrics); int realHeight = metrics.heightPixels; if (realHeight > usableHeight) return realHeight - usableHeight; else return 0; } return 0; }
所以设备的最终高度为:
int height = displayMetrics.heightPixels + getNavigationBarHeight();