我创建了一些自定义元素,并希望以编程方式将它们放置在右上角(距离上边缘n个像素,距离右边缘m个像素)。因此,我需要获得屏幕宽度和屏幕高度,然后设置位置:
int px = screenWidth - m;
int py = screenHeight - n;
如何在主活动中获取screenWidth和screenHeight?
我创建了一些自定义元素,并希望以编程方式将它们放置在右上角(距离上边缘n个像素,距离右边缘m个像素)。因此,我需要获得屏幕宽度和屏幕高度,然后设置位置:
int px = screenWidth - m;
int py = screenHeight - n;
如何在主活动中获取screenWidth和screenHeight?
当前回答
我发现这起了作用。
Rect dim = new Rect();
getWindowVisibleDisplayFrame(dim);
其他回答
科特林
fun getScreenHeight(activity: Activity): Int {
val metrics = DisplayMetrics()
activity.windowManager.defaultDisplay.getMetrics(metrics)
return metrics.heightPixels
}
fun getScreenWidth(activity: Activity): Int {
val metrics = DisplayMetrics()
activity.windowManager.defaultDisplay.getMetrics(metrics)
return metrics.widthPixels
}
创建一个类和方法,如下所示:
public MyPoint getScreenDimensionsAsPixel(Context context){
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
return new MyPoint(point.x, point.y);
}
public class MyPoint{
private int width;
private int height;
public MyPoint(int width, int height) {
this.width = width;
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
然后在代码中使用它们:
MyPoint myPoint = getScreenDimensionsAsPixel(MainActivity.this);
Toast.makeText(MainActivity.this, "width: " + String.valueOf(myPoint.getWidth()) + "|" +
"height: " + String.valueOf(myPoint.getHeight()), Toast.LENGTH_LONG).show();
简单的功能与较低版本兼容。
/**
* @return screen size int[width, height]
*
* */
public int[] getScreenSize(){
Point size = new Point();
WindowManager w = getWindowManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2){
w.getDefaultDisplay().getSize(size);
return new int[]{size.x, size.y};
}else{
Display d = w.getDefaultDisplay();
//noinspection deprecation
return new int[]{d.getWidth(), d.getHeight()};
}
}
要使用:
int width = getScreenSize()[0];
int height = getScreenSize()[1];
我发现这起了作用。
Rect dim = new Rect();
getWindowVisibleDisplayFrame(dim);
这不是OP的答案,因为他希望以真实像素显示尺寸。我想要“设备无关像素”的尺寸,并从这里汇总答案https://stackoverflow.com/a/17880012/253938在这里https://stackoverflow.com/a/6656774/253938我想到了这个:
DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics();
int dpHeight = (int)(displayMetrics.heightPixels / displayMetrics.density + 0.5);
int dpWidth = (int)(displayMetrics.widthPixels / displayMetrics.density + 0.5);