android - 自定义android属性可以有条件语句吗?

标签 android xml attr

你们中的大多数人都知道可以在 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 程序员了解非法属性,我建议采用以下两种方法之一:

  1. (简单方法)为每个“名称”及其自己的 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>
    
  2. (更完整但更复杂)为您的 XML 创建一个 XSD 模式,这样程序员就可以根据您的规则验证 XML。 XSD 本身就是 XML,所以您只需要学习其中的元素。参见 this link有关 XSD 的更多信息,如果您也用谷歌搜索,网络上有很多信息。

关于android - 自定义android属性可以有条件语句吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16087404/

相关文章:

android - 已签名的 apk 在我的设备上不起作用

android - 全屏应用安卓

android - 更改searchview左后按钮的颜色

android - 如何将文档添加到自定义属性?

jquery - 将 attr 应用于 div 但不应用于子级 (JQuery)

android - 如何在Android中设置对话框的图标

android - 使用 'bind' 和 'app' 命名空间设置自定义属性与 Android DB 之间的区别?

c# - 如何使用 LINQ 解析此 XML?

java - Android 设备尺寸之间布局调整技术的比较

jquery - 使用 jQuery 过滤带有 on data 属性的表