我的应用程序有一个按钮以及ImageView
(钢琴键盘)排列在FrameView
中。单击钢琴键盘上的键时,通过以下方式设置topMargin和leftMargin来移动按钮:
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)noteButton.getLayoutParams();
params.setMargins(leftMargin,topMargin,0,0);
实际保证金的计算方式取决于密钥,但通常使用getHeight()
内getWidth()
和onWindowFocusChanged()
获取的宽度和高度。第一个黑键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>
答案 0 :(得分:0)
getHeight()和getWidth()在你的情况下出错了。 能否请您显示更多关于如何使用getHeight()和getWidth()的代码?
获得宽度和高度的正确方法是:
view.getLayoutParams().height
view.getLayoutParams().width