res\values\attrs.xml: Error: Found item Attr/text more than one time 编译报错解决方案

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/An_Times/article/details/88130265

今天在做自定义控件的时候定义自定义属性遇到一个问题,自定义属性重复编译报错了,我是这么写的,

    <declare-styleable name="TextButtonView">
        <attr name="text" format="string"/>
        <attr name="textSize" format="dimension"/>
        <attr name="textColor" format="color"/>
        <attr name="background" format="reference"/>
    </declare-styleable>
    <declare-styleable name="CountdownView">
        <attr name="countdownstate" format="boolean" />
        <attr name="text" format="string"/>
        <attr name="countTextSize" format="dimension"/>
        <attr name="countTextColor" format="color"/>
        <attr name="countBackground" format="reference"/>
    </declare-styleable>

解决办法是将相同的属性定义到declare-styleable标签外面,这样就可以重复使用了,这样写可以解决问题

    <attr name="text" format="string"/>
    <declare-styleable name="TextButtonView">
        <attr name="text" />
        <attr name="textSize" format="dimension"/>
        <attr name="textColor" format="color"/>
        <attr name="background" format="reference"/>
    </declare-styleable>
    <declare-styleable name="CountdownView">
        <attr name="countdownstate" format="boolean" />
        <attr name="text" />
        <attr name="countTextSize" format="dimension"/>
        <attr name="countTextColor" format="color"/>
        <attr name="countBackground" format="reference"/>
    </declare-styleable>

网上也有很多这么写的,既然抽出公共的属性可行,那么为什么在一个项目中不定义一个标签,把我们的自定义属性写在一个标签里面呢

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomeAttrs">
        <attr name="text" format="string"/>
        <attr name="countdownstate" format="boolean" />
        <attr name="textSize" format="dimension"/>
        <attr name="textColor" format="color"/>
        <attr name="background" format="reference"/>
    </declare-styleable>

    <!--<declare-styleable name="TextButtonView">-->
        <!--<attr name="text" />-->
        <!--<attr name="textSize" format="dimension"/>-->
        <!--<attr name="textColor" format="color"/>-->
        <!--<attr name="background" format="reference"/>-->
    <!--</declare-styleable>-->
    <!--<declare-styleable name="CountdownView">-->
        <!--<attr name="countdownstate" format="boolean" />-->
        <!--<attr name="text" />-->
        <!--<attr name="countTextSize" format="dimension"/>-->
        <!--<attr name="countTextColor" format="color"/>-->
        <!--<attr name="countBackground" format="reference"/>-->
    <!--</declare-styleable>-->
</resources>

像这样验证过写是可行,写一次属性就可以了,不用重新定义多次,简单省事 !!!

猜你喜欢

转载自blog.csdn.net/An_Times/article/details/88130265