android - styles.xm中的自定义属性
我创建了一个自定义小部件,我在layout.xml中声明它。 我还在attr.xml中添加了一些自定义属性。 但是,当尝试在styles.xml中的样式中声明这些属性时,它给了我xmlns:custom="http://schemas.android.com/apk/res/com.my.package"
我已将xmlns:custom="http://schemas.android.com/apk/res/com.my.package"放在styles.xml中的所有标签中,包括<?xml>,和
但是,我可以使用我的命名空间手动为layout.xml中的视图分配属性,因此命名空间没有任何问题。 我的问题在于使styles.xml知道我的attr.xml。
5个解决方案
344 votes
我想到了! 答案是不在样式中指定名称空间。
<?xml version="1.0" encoding="utf-8" ?>
wrap_content
wrap_content
value
styler1972 answered 2019-04-21T21:43:40Z
37 votes
上面的答案对我有用,我尝试了一个小小的改变,我在资源元素中声明了一个类的样式。
在declare-styleable中,name属性引用了一个类名,所以我有一个视图类调用“com.my.package.name.VerticalView”,它表示这个声明必须在VerticalView或VerticalView的子类中使用。 所以我们可以这样声明样式:
match_parent
36dip
28sp
#ff666666
true
这就是为什么我们没有在resources元素声明名称空间,它仍然有效。
VinceStyling answered 2019-04-21T21:44:18Z
8 votes
Styler和vince的修改对我有用。 我想指出@ vince的解释可能并不完全准确。
为了测试与自定义视图类的名称匹配的declare-styleable的name属性允许我们访问没有命名空间的自定义属性的假设,我更改了declare-styleable的名称(自定义视图名为TestViewFont:
然后我在自定义视图中更改了declare-styleable调用以反映这一点:
TypedArray ta = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TextViewFont2, 0, 0);
代码仍在运行。 所以我不认为这是以它所命名的类declare-styleable的某种内省。
因此,我被认为可以使用任何自定义属性来声明样式而不引用命名空间。
无论如何,感谢所有帮助人员,它解决了我的问题。
Abid H. Mujtaba answered 2019-04-21T21:45:16Z
2 votes
价值观/ styles.xml
...
@color/red
@dimen/dp_100
值/ attrs.xml
值/ colors.xml
#f00
值/ dimens.xml
100dp
运用
android:layout_width="wrap_content"
android:layout_height="?attr/defaultButtonHeight"
android:text="Button"
android:textColor="?attr/defaultButtonColor"
/>
DEMO
Phan Van Linh answered 2019-04-21T21:45:59Z
1 votes
如果它帮助其他人,我的错误是我的自定义视图类调用AttributeSet.getAttributeValue,例如
String fontName = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "customFont");
...这导致我的自定义属性没有被我的自定义视图读入。
修复是在我的自定义视图中使用R.styleable.MyTextViewStyleable_customFont:
TypedArray styleAttrs = context.obtainStyledAttributes(attrs, R.styleable.MyTextViewStyleable);
String fontName = styleAttrs.getString(R.styleable.MyTextViewStyleable_customFont);
一个正常工作的提示是你可以按Ctrl / Apple +点击R.styleable.MyTextViewStyleable_customFont直接进入你的attrs.xml定义。
我花了一段时间来发现我的代码和其他示例之间的这种关键差异,因为自定义属性在直接通过布局XML(而不是通过样式)传递时工作正常。
Dan J answered 2019-04-21T21:46:50Z