java - 如何让视图显示在屏幕中的随机位置(适应不同的屏幕尺寸)
问题描述
我已经有一种方法可以在屏幕的随机位置显示按钮,但它不适用于其他屏幕尺寸。我该怎么做(内部: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);
我只希望随机数能够适应每个屏幕尺寸。
解决方案
Android 坐标基于视图的左上角。因此,您提供给视图的 x 和 y 值实际上是视图左上角的 x 和 y。尝试将nextInt()
' 参数限制为类似的值,random.nextInt(maxScreenWidth - buttonWidth)
并将random.nextInt(maxScreenHeight-buttonHeight)
这些坐标分配给按钮的 x 和 y。
推荐阅读
- python - 如何处理不一致的 CSV 列
- javascript - 如何从谷歌脚本发送错误状态代码,如错误请求(400)?
- python - 如何使用 Python 创建列并将键和值设置为 redis
- python - 单击 Selenium 中的链接:find_element_by_link_text 不起作用
- mysql - 如何设计一个航班搜索停机数据库?
- consul - consul 将 Sidecar 与 Spring Boot 微服务连接起来
- bash - 如何使用 xml 文件中的 shell 命令删除 XML 节点
- react-native - 如何在本机反应中获取或访问功能组件中的导航参数
- cuda - CUDA 11 中的链接时优化 - 它们是什么以及如何使用它们?
- javascript - TypeError: nock(...).persist(...).log 不是函数