3

I want to use some predefined dimensions from my dimens.xml file in my programmatic layout.

So for instance, in my dimens.xml file I have:

<dimen name="margin1">40dip</dimen>
<dimen name="margin2">40dip</dimen>

And then in my programmatic textview I have:

RelativeLayout.LayoutParams lpMargin = new RelativeLayout.LayoutParams( R.dimen.margin1, R.dimen.margin2);

Applying the layout parameter to my textview results in an enormous view.

I already found the problem. If I print out:

Log.e("Metrics", "margin width = " +  String.valueOf(R.dimen.margin1));

...it gives an enormous value: margin width = 2131034112. The thing that's messing it up is the units, "dip".

So my question is: what's the correct way to specify dimensions without units for calling programmatically? If that's not possible, can I alter R.dimen.margin1 so I can use it as a programmatic layout parameter?

EDIT: It wasn't the units messing it up -- it's returning the internal ID! (As ianhanniballake says below, I needed to call with getResources().getDimension(R.dimen.margin1)).

4

1 回答 1

14

利用

getResources().getDimension(R.dimen.margin1)

或者

getResources().getDimensionPixelSize(R.dimen.margin1)

您的代码返回分配给“R.dimen.margin1”的内部 ID,而不是您在 XML 文件中分配的值。

于 2013-03-01T03:02:07.507 回答