Placing a button on top of an ImageView that stretches to different screen sizes
I have an image (match_parent) with 2 rectangulars containing options. I am trying to place 2 transparent buttons at the top of an image so that clicking on the image will trigger an action. However, I am trying to support multiple screen sizes, so while I was able to experiment with layout margins to align rectangulars in buttons for a smartphone with a specific resolution, tablet testing completely failed.
How to place buttons that consistently match the image stretching to fill the screen of different sizes.
Quite simple mock 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'm using:
(source: trillian.im )
source to share
You can omit the two button images from the background image (just leave white space) and make them separate images. Then you can put them on two ImageButton
s. This solves the immediate problem of absolutely pixel perfect alignment.
To label and position these 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 ViewGroup
) and inject a method onLayout(...)
to place these two buttons in the desired area of the background image, applying those percentages to whatever your view size is.
This custom ViewGroup might look something like this:
public class Blah extends ViewGroup {
Button b1;
@Override
protected void onFinishInflate() {
super.onFinishInflate();
b1 = (Button) findViewById(R.id.button_1);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// In dimensions XML: <fraction name="button_margin_horizontal">20%p</fraction>
int left = (int) getResources().getFraction(R.fraction.button_margin_horizontal, 0, getWidth());
int right = getWidth() - left;
int buttonHeight = b1.getMeasuredHeight();
b1.layout(left, 0, right, buttonHeight);
}
}
source to share