我希望我的ViewA和ViewB都有"标题"标签.但我不能把它放进去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>
Run Code Online (Sandbox Code Playgroud)
因为错误属性"标题"已经定义.另一个问题显示了这个解
<?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>
Run Code Online (Sandbox Code Playgroud)
但在那种情况下,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);
Run Code Online (Sandbox Code Playgroud)
我怎么解决这个问题?
在我的Android项目中,我有几个使用自定义属性的自定义组件。
attrs.xml文件如下所示:
<?xml version="1.0" encoding="utf-8"?>
<resources >
<declare-styleable name = "TextBox">
<attr name = "font" format = "string"/>
</declare-styleable>
<declare-styleable name = "ButtonBox">
<attr name = "font" format = "string"/>
</declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)
我在自定义组件中输入的属性很好,但是当我运行代码时,看到以下错误。
错误:多次发现Attr / font项目
错误:任务':app:mergeDebugResources'执行失败。
在两个不同的可声明样式的资源中有相似的属性名称,对吗?
如果您有任何帮助,将不胜感激,谢谢!
如果我导入:
CustomViewA(从Maven导入)
<declare-styleable name="CustomViewA">
<attr name="min" format="float"/>
<attr name="max" format="float"/>
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)
CustomViewB(从Maven导入)
<declare-styleable name="CustomViewB">
<attr name="min" format="float"/>
<attr name="max" format="float"/>
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)
这将失败,说明min和max重复。我以为 Android 会通过 来区分declare-styleable name,但我猜不会。话虽如此,命名自定义视图attr以避免将来可能出现的重复值冲突的最佳方法是什么?
到目前为止我得到的唯一解决方案是:
<attr name="minForMyCustomViewHopingNoOneUsesThisName" format="float"/>
Run Code Online (Sandbox Code Playgroud)
这很糟糕。
android android-custom-view android-styles android-attributes