关于declare-styleable标记的珍贵文档很少,我们可以通过它来声明组件的自定义样式.我确实找到了这个标签format属性的有效值列表attr.虽然这很好,但它没有解释如何使用其中的一些值.浏览attr.xml(标准属性的Android源代码),我发现你可以做以下事情:
<!-- The most prominent text color. -->
<attr name="textColorPrimary" format="reference|color" />
Run Code Online (Sandbox Code Playgroud)
该format属性显然可以设置为值的组合.据推测,该format属性有助于解析器解释实际的样式值.然后我在attr.xml中发现了这个:
<!-- Default text typeface. -->
<attr name="typeface">
<enum name="normal" value="0" />
<enum name="sans" value="1" />
<enum name="serif" value="2" />
<enum name="monospace" value="3" />
</attr>
<!-- Default text typeface style. -->
<attr name="textStyle">
<flag name="normal" value="0" />
<flag name="bold" value="1" />
<flag name="italic" value="2" />
</attr>
Run Code Online (Sandbox Code Playgroud)
这两个似乎都声明了一组指定样式的允许值.
所以我有两个问题:
enum值之一的样式属性与可以采用一组值的样式属性之间的区别是什么flag? …我希望我的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)
我怎么解决这个问题?
这是我正在使用的代码:
public ASSwitch(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray sharedTypedArray = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.ASSwitch,
0, 0);
try {
onText = sharedTypedArray.getText(R.styleable.ASSwtich_onText, null);
} finally {
sharedTypedArray.recycle();
}
}
Run Code Online (Sandbox Code Playgroud)
这是attrs.xml文件(添加到values文件夹):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ASSwitch">
<attr name="onText" format="string" />
<attr name="offText" format="string" />
<attr name="onState" format="boolean" />
<attr name="toogleDrawable" format="string" />
<attr name="frameDrawable" format="string" />
</declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)
这些问题的答案无法解决问题。请不要认为我的问题是重复的。
更新:似乎我导入了错误的R类。它R不是应用程序的类android.R。