首页 > 解决方案 > 如何让视图显示在屏幕中的随机位置(适应不同的屏幕尺寸)

问题描述

我已经有一种方法可以在屏幕的随机位置显示按钮,但它不适用于其他屏幕尺寸。我该怎么做(内部:r.nextInt())。

int buttonHeight;
int buttonWidth;
buttonHeight = button.getHeight();
buttonWidth = button.getWidth();
int xLeft = r.nextInt(480 - buttonHeight);
int yUp = r.nextInt(500 - buttonWidth);
int xRight = r.nextInt(670 + buttonHeight);
int yDown = r.nextInt(1400 + buttonWidth);

button.setX(xLeft);
button.setY(yUp);
button.setX(xRight);
button.setY(yDown);

我只希望随机数能够适应每个屏幕尺寸。

标签: javaandroid-studioandroid-studio-3.0

解决方案


Android 坐标基于视图的左上角。因此,您提供给视图的 x 和 y 值实际上是视图左上角的 x 和 y。尝试将nextInt()' 参数限制为类似的值,random.nextInt(maxScreenWidth - buttonWidth)并将random.nextInt(maxScreenHeight-buttonHeight)这些坐标分配给按钮的 x 和 y。


推荐阅读