My application has a button as well as an ImageView
(of a piano keyboard) arranged in a FrameView
. When a key on the piano keyboard is clicked, the button gets moved there by setting it's topMargin and leftMargin via the following:
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)noteButton.getLayoutParams();
params.setMargins(leftMargin,topMargin,0,0);
The actual margin is calculated differently depending on the key, but generally uses the Width and Height aquired via getHeight()
and getWidth()
within onWindowFocusChanged()
. The calculation for the first black key, C# or Db, looks like the following:
leftMargin = (int) (pianoImageViewWidth/7 - buttonSize/2);
Since the piano graphic is 7 keys wide and the black key is between the first and second key (see image).
My problem now is the actual margins are not centered; they're actually somewhat far off, like in the following example.
It is generally worse towards the left side of the keyboard. On smaller dp devices, it's so far to the left it's out of the bounds of the black key. I absolutely cannot figure out what is going wrong there, I hope somebody here can help me adjust this.
Additionally, here is the code to get the width and height:
int pianoImageWidth = imagePiano.getWidth();
int pianoImageHeight = imagePiano.getHeight();
int buttonSize = noteButton.getWidth();
And the XML of the actual piano and button:
<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>