Arbiter of buffoonery
Arbiter of buffoonery

Reputation: 1655

Android XML defined dimension value yielding unexpected results

I have defined a dp dimension in my XML file like so:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="custom_button_Margin">10dp</dimen>
</resources>

The idea being that I use these values to set the padding between elements. This works fine when I use the value in my layout XML file.

Snippet:

<RelativeLayout
    android:id="@+id/mainButtons"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="0.4"
    android:layout_margin = "5dp"

    android:gravity="right|bottom">
    <Button
        android:id="@+id/_7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/seven"

        android:background = "@drawable/custom_button"
        android:typeface="monospace"
        android:textSize="@dimen/custom_button_TextSize"

        android:layout_marginRight = "@dimen/custom_button_Margin"
        android:layout_marginBottom = "@dimen/custom_button_Margin"
    />
</RelativeLayout>

The problem lies when I attempt to get this value programmatically. I expect to get a value that has been scaled to match the screen density. Then all I would do is follow the formula found here (the page is quite long look for Converting dp units to pixel units)

I wrapped the formula in a function that retrieves the value defined in the file, and scales it to pixels.

private int get_custom_button_PadV()
    {
    final float scale = getResources().getDisplayMetrics().density;

    return (int) (R.dimen.custom_button_Margin * scale + 0.5f);
    }

When I watch the code, I see the following values

scale = 1.0
R.dimen.custom_button_Margin = 2131099650

I can't figure out why the custom_button_Margin value is so large...I would expect that with a scale of 1.0, that there would be a value of 10. What am I missing?

Upvotes: 4

Views: 4581

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234795

You are using the dimension ID as the dimension value. Try this instead:

private int get_custom_button_PadV() {
    final Resources res = getResources();
    final float scale = res.getDisplayMetrics().density;
    return (int) (res.getDimension(R.dimen.custom_button_Margin) * scale + 0.5f);
}

Upvotes: 8

Related Questions