0

I'm trying to get the margins from the .xml file. Currently I'm doing it like so:

mUserDefinedLeftMargin = attrs.getAttributeIntValue("http://schemas.android.com/apk/res/android", "layout_marginLeft", 0);

where attrs is of type AttributeSet (it's received in the constructor or my class which extends RelativeLayout)

The .xml looks like this:

    <ch......MyCustomView
        android:id="@+id/update_progress"
        android:layout_width="400dp"
        android:layout_height="200dp"
        android:layout_marginLeft="10dp"
        android:layout_alignParentRight="true"
        android:visibility="invisible" />

mUserDefinedLeftMargin is still 0 at the end of the above call. Why ?

AndreiBogdan
  • 10,858
  • 13
  • 58
  • 106

1 Answers1

1

It is because dp is not int value. You should first get it as text:

String dpSizeText = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "layout_marginLeft");

And convert it to pixels after:

int dpSizeInt = Integer.parseInt(dpSizeText.substring(0, dpSizeText.indexOf("dp")));
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpSizeInt, r.getDisplayMetrics());
Eugen Martynov
  • 19,888
  • 10
  • 61
  • 114
  • @AndreiBogdan please don't do that, use Context.obtainStyledAttributes(AttributeSet set, int[] attrs) instead – pskink Jul 11 '14 at 10:42