Placing Button on top of ImageView that stretches with different screen sizes

135 views Asked by At

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: options
(source: trillian.im)

1

There are 1 answers

0
Barend On

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 ImageButtons. 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 the onLayout(...) 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:

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);
    }
}