【问题标题】:How to position buttons on scaled background image如何在缩放的背景图像上放置按钮
【发布时间】:2013-11-28 16:59:42
【问题描述】:

从 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(),但我宁愿继续使用实际按钮,以便键盘导航和按下/悬停效果按预期工作。

如何定位按钮,让它们始终与位图匹配比例? 感谢您提供任何见解。

由于标题,这个问题看起来像个骗子,但我还没有找到任何可以证明如何完成的问题。

【问题讨论】:

  • 为什么不尝试相对布局而不是网格布局?

标签: android android-layout android-studio


【解决方案1】:

我遇到了这个问题,我用数学方法解决了这个问题。这非常可怕,但是假设您的背景图像是 500x500 像素,并且在这样的图像上,您的按钮应该位于 (100, 100) 处,相对于该背景图像的大小为 50x50 像素。布局时,您必须获取当前设备的大小,假设它的大小为 700x800 像素(这些设备很可能不存在)。在这种情况下,您必须将按钮的宽度设置为 (700/500)*50px ,高度设置为 (800/500)*50px 。然后按钮的位置将位于 (700/500)*100 和 (800/500)*100 。

您几乎可以使用背景图像缩放按钮。希望我能说清楚:)

【讨论】:

    【解决方案2】:

    你可以试试这个,希望对你有帮助

    <ImageButton
    android:id="@+id/notificationform_btn_Approve"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:layout_height="wrap_content"
    android:src="@drawable/btn_approve"
    android:onClick="btnApprove_Click" />
    

    看看here

    你为什么不改用 ImageButton:

    <ImageButton android:src="@drawable/greybutton"
            android:scaleType="fitCenter" android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    

    然后您可以使用 scaleType 属性调整缩放比例。唯一的缺点是您不能设置任何文本。 祝你好运

    【讨论】:

    • 我看不出这有什么帮助,我需要 4 个普通按钮放在一个位图上。罪魁祸首是这些比例与位图位置和比例相匹配。
    猜你喜欢
    • 1970-01-01
    • 2014-01-13
    • 2011-12-29
    • 2014-04-09
    • 2011-02-19
    • 2012-09-24
    • 2012-01-03
    • 2012-07-08
    相关资源
    最近更新 更多