我希望我的ViewA和ViewB都有"title“标签。但我不能把这个放进attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ViewA">
<attr name="title" format="string" />
</declare-styleable>
<declare-styleable name="ViewB">
<attr name="title" format="string" />
<attr name="max" format="integer" />
</declare-styleable>
</resources>因为错误属性"title“已经定义好了。Another question展示了这个解决方案:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="title" format="string" />
<declare-styleable name="ViewB">
<attr name="max" format="integer" />
</declare-styleable>
</resources>但在这种情况下,不会生成R.styleable.ViewA_title和R.styleable.ViewB_title。我需要它们来使用以下代码从AttributeSet读取属性:
TypedArray a=getContext().obtainStyledAttributes( as, R.styleable.ViewA);
String title = a.getString(R.styleable.ViewA_title);我怎么才能解决这个问题?
发布于 2013-09-19 06:51:58
你发布的链接确实给了你正确的答案。这就是它建议你做的:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="title" format="string" />
<declare-styleable name="ViewA">
<attr name="title" />
</declare-styleable>
<declare-styleable name="ViewB">
<attr name="title" />
<attr name="max" format="integer" />
</declare-styleable>
</resources>现在,R.styleable.ViewA_title和R.styleable.ViewB_title都是可访问的。
如果你有机会,读一遍这个答案:Link。相关引文:
您可以在顶层元素或元素内部定义属性。如果我要在多个地方使用一个attr,我就把它放在根元素中。
发布于 2017-04-26 13:01:21
代之而行。不需要parent标签
<resources>
<declare-styleable name="ViewA">
<attr name="title" format="string" />
</declare-styleable>
<declare-styleable name="ViewB" >
<attr name="title" />
<attr name="min" format="integer" />
<attr name="max" format="integer" />
</declare-styleable>
</resources>这是因为一旦title在ViewA中声明,它就不需要(也不能)在另一个declare-styleable中再次声明
发布于 2017-11-13 10:41:02
<resources>
<declare-styleable name="ViewA">
<attr name="title" format="string" />
</declare-styleable>
<declare-styleable name="ViewB" parent="ViewA"> // inherit from ViewA
<attr name="min" format="integer" />
<attr name="max" format="integer" />
</declare-styleable>
这不管用。
<resources>
<attr name="title" format="string" />
<declare-styleable name="ViewA">
<attr name="title" />
</declare-styleable>
<declare-styleable name="ViewB">
<attr name="title" />
<attr name="max" format="integer" />
</declare-styleable>这也没用。
<resources>
<declare-styleable name="ViewA">
<attr name="title" format="string" />
</declare-styleable>
<declare-styleable name="ViewB" >
<attr name="title" />
<attr name="min" format="integer" />
<attr name="max" format="integer" />
</declare-styleable>,这很好!!
https://stackoverflow.com/questions/18827875
复制相似问题