【问题标题】:Retrieve margins from attributes从属性中检索边距
【发布时间】: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


【解决方案1】:

这是因为 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());

【讨论】:

  • @AndreiBogdan 请不要那样做,使用 Context.obtainStyledAttributes(AttributeSet set, int[] attrs) 代替
猜你喜欢
  • 2011-01-18
  • 2014-10-07
  • 1970-01-01
  • 2016-12-11
  • 2018-10-06
  • 2023-03-10
  • 2012-08-13
  • 2010-11-03
  • 2015-07-16
相关资源
最近更新 更多