Android 从属性中检索边距
我正在尝试从Android 从属性中检索边距,android,Android,我正在尝试从.xml文件中获取边距。目前我是这样做的: mUserDefinedLeftMargin = attrs.getAttributeIntValue("http://schemas.android.com/apk/res/android", "layout_marginLeft", 0); 其中attrs的类型为AttributeSet(它在扩展RelativeLayout的构造函数或我的类中接收) .xml如下所示: <ch......MyCustomView
.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值。您应该首先将其作为文本获取:
String dpSizeText = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "layout_marginLeft");
并在以下时间后将其转换为像素:
int dpSizeInt = Integer.parseInt(dpSizeText.substring(0, dpSizeText.indexOf("dp")));
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpSizeInt, r.getDisplayMetrics());
这是因为dp不是int值。看一看。它是字符串,你应该把它转换成点!请将其作为响应编写,这样我就可以接受它。如果不这样做,请使用上下文。取而代之的是获取StyledAttributes(AttributeSet,int[]attrs),无需将“14.0sp”之类的字符串转换为floatvalue@pskink你能写一个答案吗?@EugenMartynov只需使用TypedArray.getDimension*()就可以得到浮点值value@AndreiBogdan请不要那样做,改为使用Context.obtainStyleDatAttributes(AttributeSet,int[]attrs)