(Android) How can I get the SmartPhone screen bus and height?

I am making an Android game and am using SurfaceView.

I want to know the information on the SmartPhone screen (height, width, etc.)

I used this code, but .. This is an incorrect value for the width and height of the display,

He always printed “0” with red

What am I missing?

public class MainActivity extends Activity { private int width; private int height; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); width = metrics.widthPixels; height = metrics.heightPixels; setContentView(new GameView(this)); } public class Painter extends Thread public void run(){ Canvas canvas = null; long start, end; int sleep; while(true) { if (runnable) { start = System.currentTimeMillis(); try { canvas = holder.lockCanvas(null); paint.setColor(Color.RED); paint.setTextSize(200); synchronized (holder) { canvas.drawText(Integer.toString(main.getHeight()), 600, 800, paint); canvas.drawText(Integer.toString(main.getWidth()), 300, 400, paint); } } catch (Exception e) { e.printStackTrace(); } finally { holder.unlockCanvasAndPost(canvas); } end = System.currentTimeMillis(); sleep = 1000 / FPS - (int) (end - start); try { Thread.sleep(sleep > 0 ? sleep : 0); } // Try catch (InterruptedException e) { e.printStackTrace(); } } } 
+5
source share
4 answers

You can get it with this code:

 DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int height = displaymetrics.heightPixels; int width = displaymetrics.widthPixels; 

It works with all versions of the API and therefore does not require an API check. If you have a view, you may need context:

 ((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);‌​ 
+4
source

You can get the height and width of the display using the following code.

  Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int width = size.x; int height = size.y; 
+1
source
  /* * A structure describing general information about a display, such as its size, density, and font scaling. * */ DisplayMetrics metrics = getResources().getDisplayMetrics(); int DeviceTotalWidth = metrics.widthPixels; int DeviceTotalHeight = metrics.heightPixels; 

How to get the height and width of a device at runtime?

+1
source
 DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int width=dm.widthPixels; int height=dm.heightPixels; int dens=dm.densityDpi; double wi=(double)width/(double)dens; double hi=(double)height/(double)dens; double x = Math.pow(wi,2); double y = Math.pow(hi,2); double screenInches = Math.sqrt(x+y); 
0
source

Source: https://habr.com/ru/post/1238347/


All Articles