如何知道是否定义了XML属性?

时间:2012-04-05 13:38:02

标签: android android-layout

我有一个自定义TextView,我想在构造函数中找出是否在相应的xml布局中声明了某个XML属性。

<com.stuff.CustomTextView
  android:id="@+id/tv01"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:textSize="8sp" />

public CustomTextView(Context context, AttributeSet attrs) {
   super(context, attrs);
   // find out if textSize was defined
   if (!wasAttributeDefined(attrs,"textSize")) // EDIT
     setTextSize(10); // EDIT
}

我不知道这是否有效,但我尝试了以下(没有运气):

attrs.getAttributeFloatValue("android","textSize",(float)-1.0);

感谢。

编辑:

好吧,如果有人有兴趣,有一种(可能不太好)解决这个问题的方法。喜欢:

private boolean wasAttributeDefined(AttributeSet attrs, String name) {
    for (int i=0; i<attrs.getAttributeCount(); i++)
        if (attrs.getAttributeName(i).equals(name))
            return true;
    return false;
}

1 个答案:

答案 0 :(得分:0)

您应该使用以下内容测试您的属性:

R.id.tv01.attr.textSize