Android 如何知道是否定义了XML属性?
我有一个自定义的TextView,我想在构造函数中找出是否在相应的XML布局中声明了某个XML属性Android 如何知道是否定义了XML属性?,android,android-layout,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
<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
}
谢谢
编辑:
好吧,如果有人感兴趣,有一个(可能不是很好的)解决方法。比如:
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;
}
private boolean wasAttributeDefined(AttributeSet attrs,字符串名){
对于(int i=0;i,您应该使用以下方法测试属性:
R.id.tv01.attr.textSize
您是否放置了日志?是否有错误?没有错误。仅获取我提供的默认值(-1.0),尽管已经在XML中定义了android:textSize。这将为您提供id为Tv01的小部件的属性android:textSize中设置的值。问题是,我想知道是否每次在构造函数中出现“新”CustomTextView时(在XML中)都声明了属性,而不是针对单个/特定的属性。
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;
}