【问题标题】:Can there be conditional statements on custom android attributes?自定义android属性可以有条件语句吗?
【发布时间】:2013-04-18 15:42:45
【问题描述】:

大多数人都知道在 Android 中可以为自定义视图提供自定义属性。这在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 在他的回答中提出的建议:创建具有不同名称的各种自定义视图,并让它们只具有属于它们的属性。

但是我非常问自己是否有可能不首先混淆 .xml 文件的程序员,而只向他提供他真正需要的东西组合在一个地方。毕竟这 以某种方式已经由 Android(嗯...... IDE / Lint / Parser......)提示例如应该将视图的宽度或高度设置为0dp 使用 layout_weight 时。

但如果我不得不猜测的话,我会说这可能只有在我重写 Android XML-Parser 时才有可能......有人可以证明我错了吗?

提前致谢

【问题讨论】:

  • 你做错了
  • “是否可以仅在满足另一个条件时才呈现此类属性?” -- AFAIK,不。

标签: android xml attr


【解决方案1】:

如果我理解正确,您有一个自定义视图,可以在第三个属性上获得不同的属性条件。

为了让 XML 程序员了解非法属性,我建议使用以下两种方法之一:

  1. (简单方法)为每个“名称”和每个自己的declare-styleable 组创建一个自定义视图。

    <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,因此您只需学习元素。有关 XSD 的更多信息,请参阅this link,如果您也使用 google 搜索,网络上有很多信息。

【讨论】:

  • 是的,您理解正确。方法 1. 是我目前使用的临时解决方案。我会在有时间研究 XSD 后立即报告,非常感谢您
  • @avalancha 请记住,通过方法 2,您可以做您想做的事情以及更多。付出的代价是你必须学会​​如何正确地写它。如果您使用 Eclipse,那么您会注意到在编辑 XML 文件时,您可以从右键单击上下文菜单中对其进行验证。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-03
  • 2017-12-03
  • 1970-01-01
  • 2017-11-26
  • 1970-01-01
  • 1970-01-01
  • 2010-11-20
相关资源
最近更新 更多