【发布时间】:2014-07-11 18:21:03
【问题描述】:
我正在尝试从.xml 文件中获取边距。目前我正在这样做:
mUserDefinedLeftMargin = attrs.getAttributeIntValue("http://schemas.android.com/apk/res/android", "layout_marginLeft", 0);
其中attrs 的类型为AttributeSet(它在构造函数或我的扩展RelativeLayout 的类中接收)
.xml 看起来像这样:
<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 在上述调用结束时仍为 0。为什么?
【问题讨论】:
-
这是因为 dp 不是 int 值。看看stackoverflow.com/questions/8302229/…。它是字符串,您应该自己将其转换为点
-
太棒了!请把它写成回复,所以我可以接受它
-
不要那样做,使用 Context.obtainStyledAttributes(AttributeSet set, int[] attrs) 代替,不需要将像“14.0sp”这样的字符串转换为浮点值
-
@pskink 你能写一个答案吗?
-
@EugenMartynov 只需使用 TypedArray.getDimension*() 获取浮点值
标签: android