I have an image (match_parent) with 2 rectangles in it containing options. I am trying to place 2 transparent buttons on top of the image so that clicking on the image results in an action. However, I am trying to support multiple screen sizes, so while I was able to play around with layout margins to line up the rectangles in the buttons for a specific resolution smartphone, testing a tablet completely failed.
How do I place buttons that consistently line up with an image that stretches to fill varying screen sizes.
Pretty simple layout code right now using dp which doesn't work
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/banner"
android:background="@drawable/banner"
android:contentDescription="@string/banner" />
<Button
android:layout_width="120dp"
android:layout_height="90dp"
android:id="@+id/vs_computer"
android:layout_marginTop="135dp"
android:layout_marginLeft="135dp"
android:alpha="0"
android:clickable="true"
android:shadowColor="@android:color/transparent"
android:singleLine="true" />
<Button
android:layout_width="120dp"
android:layout_height="100dp"
android:id="@+id/multiplayer"
android:layout_marginTop="260dp"
android:layout_marginLeft="135dp"
android:alpha="0"
android:clickable="true"
android:shadowColor="@android:color/transparent"
android:singleLine="true" />
The temporary image I am using:
(source: trillian.im)
You could omit the two button graphics from the background image (just leave a blank space) and make them separate images. You can then put those on two
ImageButton
s. This solves the immediate problem of having to line up absolutely pixel perfectly.To size and position those buttons, figure out what their left/right and top/bottom margins are as a percentage of the screen width and height. You can then create a custom layout (subclass of
ViewGroup
) and implement theonLayout(...)
method to position those two buttons within the desired region of the background image by applying those percentages to whatever your view size happens to be.That custom ViewGroup could look something like this: