I'm making game for Android and use SurfaceView.
I want to know SmartPhone Screen Info(Height, Width, ect..)
I uesd this code, but.. It is not correct value of display Width and Height,
It's always printed "0" by Red Color
What I miss?
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();
}
}
}
Display display = getWindowManager(). getDefaultDisplay(); Point size = new Point(); display. getSize(size); int width = size. x; int height = size.
The best way to create a responsive layout is to use ConstraintLayout as the base layout in your UI. ConstraintLayout enables you to specify the position and size of each view according to spatial relationships with other views in the layout. All the views can then move and resize together as the screen size changes.
You can get it using this Code:
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
Works on all API versions, and therefore requires no API checking. If you are in a view, you might need to get the context:
((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With