【问题标题】:How to avoid duplicate value for resource 'attr/*' in CustomView如何避免 CustomView 中资源“attr/*”的重复值
【发布时间】:2020-02-21 11:32:27
【问题描述】:

如果我导入:

CustomViewA(从 Maven 导入)

<declare-styleable name="CustomViewA">
        <attr name="min" format="float"/>
        <attr name="max" format="float"/>
</declare-styleable>

CustomViewB(从 Maven 导入)

<declare-styleable name="CustomViewB">
        <attr name="min" format="float"/>
        <attr name="max" format="float"/>
</declare-styleable>

如果 minma​​x 重复,这将失败。我以为 Android 会通过 declare-styleable name 来区分,但我猜不是。话虽如此,命名自定义视图 attr 以避免将来任何可能的重复值冲突的最佳方式是什么?

目前我得到的唯一解决方案是:

<attr name="minForMyCustomViewHopingNoOneUsesThisName" format="float"/>

这太糟糕了。

【问题讨论】:

标签: android android-custom-view android-styles android-attributes


【解决方案1】:

你可以这样做

<attr name="min" format="float" />
<attr name="max" format="float" />

<declare-styleable name="CustomViewA">
    <attr name="min" />
    <attr name="max" />
</declare-styleable>

<declare-styleable name="CustomViewB">
   <attr name="min" />
   <attr name="max" />
</declare-styleable>

【讨论】:

  • 如果我是 CustomViewA 的所有者但不是来自 CustomViewB 的所有者,这会起作用吗?假设CustomViewB 开发人员在declare-styleable 外部和/或内部使用attr
  • 无法理解。你在说什么?
  • 假设在我的自定义库中,我使用了您的方法。然后我导入另一个使用相同方法的 Lib。会不会碰撞?
  • 抱歉耽搁了。不,它不会碰撞。如果两个库具有相同的attr elements,它将正常工作
  • 是的,它可以在不同的模块中使用不同的格式和相同的名称来正常工作
【解决方案2】:

让它独一无二是最终的答案。 我准备使用

<attr name="custom_view_a_min" format="float"/>
<attr name="custom_view_b_min" format="float"/>

【讨论】:

    猜你喜欢
    • 2018-05-21
    • 2011-04-03
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多