繁体   English   中英

如何在ImageView上正确放置按钮?

[英]How to place a Button properly over an ImageView?

我的应用程序在FrameView安排了一个按钮以及一个ImageView (钢琴键盘)。 单击钢琴键盘上的键时,可通过以下操作将其设置为topMargin和leftMargin,从而将按钮移到那里:

FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)noteButton.getLayoutParams();
params.setMargins(leftMargin,topMargin,0,0);

实际边距的计算取决于键,但是通常使用onWindowFocusChanged()通过getHeight()getWidth()获得的Width和Height。 第一个黑键C#或Db的计算如下所示:

leftMargin = (int) (pianoImageViewWidth/7 - buttonSize/2);

由于钢琴图形的宽度为7个键,而黑色键位于第一个和第二个键之间(请参见图片)。

我现在的问题是实际边距未居中; 它们实际上相差很远,如以下示例所示。

例

通常情况下,键盘左侧的情况更糟。 在较小的dp设备上,它离左侧太远了,超出了黑键的范围。 我绝对不能弄清楚那里出了什么问题,希望这里有人可以帮助我进行调整。

此外,以下是获取宽度和高度的代码:

    int pianoImageWidth  = imagePiano.getWidth();
    int pianoImageHeight = imagePiano.getHeight();
    int buttonSize = noteButton.getWidth();

以及实际钢琴和按钮的XML:

<FrameLayout
    android:id="@+id/piano_frame"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView">

    <Button
        android:id="@+id/note_button"

        android:visibility="invisible"
        android:text="C"
        android:textColor="#FFFFFF"
        android:textSize="20sp"
        android:textAlignment="center"
        android:padding="0dp"

        android:layout_width="32dp"
        android:layout_height="32dp"
        android:background="@drawable/note"
        android:shadowColor="#A8A8A8"
        android:shadowDx="0"
        android:shadowDy="0"
        android:shadowRadius="5"
        android:layout_margin="0dp"
        />

    <ImageView
        android:id="@+id/piano_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:cropToPadding="false"
        app:srcCompat="@drawable/piano" />
</FrameLayout>

我认为getHeight()和getWidth()在您的情况下出错。 您能否显示更多有关如何使用getHeight()和getWidth()的代码?

获取宽度和高度的正确方法是:

view.getLayoutParams().height
view.getLayoutParams().width

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM