获取手机屏幕宽高

1.在activity中获取

public class TActivity extends AppCompatActivity{
  @Override
  public void onCreate(
      @Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState)
  {
     super.onCreate(savedInstanceState, persistentState);
     WindowManager manager = getWindowManager();
     DisplayMetrics metrics = new DisplayMetrics();
     manager.getDefaultDisplay().getMetrics(metrics);
     int width = metrics.widthPixels;  //以要素为单位
     int height = metrics.heightPixels;
  }
}
2.在其他类中获取屏幕的宽高
public class text {
  public text(Context context) {
     -------------------------1111111-------------------	
     WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
     int width = manager.getDefaultDisplay().getWidth();
     int height = manager.getDefaultDisplay().getHeight();
     
     -------------------------2222222-----------------------
     DisplayMetrics metrics = new DisplayMetrics();
     manager.getDefaultDisplay().getMetrics(metrics);
     int width2 = metrics.widthPixels;  //以要素为单位
      int height2 = metrics.heightPixels;
     ---------------------------33333-------------------
     Point point = new Point();
     manager.getDefaultDisplay().getSize(point);
     int width3 = point.x;  //没去验证,有需要的可以打个log看下.
     int height3 = point.y;
  }
}

你可能感兴趣的:(获取手机屏幕宽高)