android:anyDensity="true"的情况用以下方法即可获取
DisplayMetrics dm = MainActivity.getActivity().getResources().getDisplayMetrics(); int w_screen = dm.widthPixels; int h_screen = dm.heightPixels;
android:anyDensity="false"的情况上用面的方法发现获得的值不是实际分辨率,在debug是发DisplayMetrics有两个属性noncompatWidthPixels和noncompatHeightPixels显示了实际分辨率,却无法直接用dm.noncompatWidthPixels这样的方法get出来用,需要用以下方法去获取
int w_screen = 0; int h_screen = 0; try { Field field = DisplayMetrics.class.getDeclaredField("noncompatWidthPixels"); field.setAccessible(true); w_screen = field.getInt(dm); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); }
h_screen可用类似上面的方法获取
Field导入的是
import java.lang.reflect.Field;