从 Android 开发开始,我想知道如何在 XML 中进行此布局(使用 Android Studio),针对 4.x Android 设备。
如何在位图背景上精确定位 4 个按钮?尽管位图缩放应该可以工作。
场景: 我的应用程序主屏幕应由放置在位图上的 4 个按钮组成。按钮位置应始终与此完全相同,并且整体应按比例放大/缩小(按比例宽度/高度)以匹配屏幕空间。布局草图:
尝试过的解决方案:
带背景的 GridLayout 中的 4 个按钮:
<GridLayout android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_centerHorizontal="true" android:orientation="horizontal" android:columnCount="2" android:rowCount="2"> <Button android:id="@+id/button1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Button1" /> <Button android:id="@+id/button2" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Button2" /> <Button android:id="@+id/button3" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Button3" /> <Button android:id="@+id/button4" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Button4" /> </GridLayout>
GridLayout 中的 4 个按钮,位于relativelayout 中的 ImageView 上方。
- 一个带有 onTouch() 的 ImageView,用于检查颜色编码的位图。 (source here)
在缩放方面唯一有效的解决方案是 onTouch(),但我宁愿继续使用实际按钮,以便键盘导航和按下/悬停效果按预期工作。
如何定位按钮,使它们始终与位图匹配比例? 感谢您提供任何见解。
由于标题,这个问题看起来像是一个骗局,但我还没有找到任何可以证明如何实现这一点的问题。
最佳答案
我遇到了这个问题,我用数学方法解决了它。这非常可怕,但假设您的背景图像是 500x500px,并且在这样的图像上,您的按钮应该位于 (100, 100),相对于该背景图像的大小为 50x50px。当你布局它时,你必须获取当前设备的大小,假设它的大小是 700x800px(这些设备很可能不存在)。在这种情况下,您必须将按钮的宽度设置为 (700/500)*50px ,高度为 (800/500)*50px 。按钮的位置将位于 (700/500)*100 和 (800/500)*100 。
您几乎用背景图像缩放了按钮。希望我能说清楚:)
关于android - 如何在缩放背景图像上放置按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19998740/