你们中的大多数人都知道可以在 Android 中为自定义 View 提供自定义属性。例如在 this thread here on Stackoverflow 中对此进行了非常精彩的解释。 .然而,我的问题是:
是否可以仅在满足另一个条件时才显示此类属性?
我的意思是这样的(伪代码):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCustomView">
<attr name="isClock" format="boolean" />
</declare-styleable>
<if name="isClock" value="true">
<attr name="timezone" format="string">
</if>
<else>
<attr name="somethingElse" format="string>
</else>
</resources>
现在不必使用“错误”属性的一种可能性是在 Java 代码中执行此操作,显然:
public class MyCustomView {
public MyCustomView(Context context) {
TypedArray styleables = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
boolean choice = styleables.getBoolean(R.styleable.MyCustomView_isClock, false);
if(choice) {
// It's a clock, react to the other attrs
} else {
// Don't react
}
styleables.recycle();
}
}
另一种方法是按照 ilomambo 在他的回答中建议的那样做:创建各种具有不同名称的自定义 View ,并让它们只具有属于它们的属性。
但我一直在问自己,是否有可能首先不混淆 .xml 文件的程序员,并只向他提供他真正需要的东西组合在一个地方。毕竟这是 Android 已经完成的方式(好吧......IDE/Lint/Parser......)当提示例如 View 的宽度或高度应设置为0dp
使用 layout_weight
时。
但如果我不得不猜测,我会说这可能只有在我重写 Android XML-Parser 时才有可能...有人可以证明我错了吗?
提前致谢
最佳答案
如果我没理解错的话,您有一个自定义 View ,它可以根据第三个属性获取不同的属性。
为了让 XML 程序员了解非法属性,我建议采用以下两种方法之一:
(简单方法)为每个“名称”及其自己的
declare-styleable
组创建一个自定义 View 。<resources> <declare-styleable name="ClockCustomView"> <attr . . . /> </declare-styleable> <declare-styleable name="OtherCustomView"> <attr . . . /> </declare-styleable> <!-- Common attributes are declared outside declare-styleable --> <attr . . . /> </resources>
(更完整但更复杂)为您的 XML 创建一个 XSD 模式,这样程序员就可以根据您的规则验证 XML。 XSD 本身就是 XML,所以您只需要学习其中的元素。参见 this link有关 XSD 的更多信息,如果您也用谷歌搜索,网络上有很多信息。
关于android - 自定义android属性可以有条件语句吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16087404/