Same-named attributes in attrs.xml for custom view
Asked Answered
G

5

225

I'm writing a few custom views which share some same-named attributes. In their respective <declare-styleable> section in attrs.xml I'd like to use the same names for attributes:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyView1">
        <attr name="myattr1" format="string" />
        <attr name="myattr2" format="dimension" />
        ...
    </declare-styleable>

    <declare-styleable name="MyView2">
        <attr name="myattr1" format="string" />
        <attr name="myattr2" format="dimension" />
        ...
    </declare-styleable>
</resources>

I'm getting an error saying that myattr1 and myattr2 are already defined. I found that I should omit the format attribute for myattr1 and myattr2 in MyView2, but if I do that, I obtain the following error in the console:

[2010-12-13 23:53:11 - MyProject] ERROR: In <declare-styleable> MyView2, unable to find attribute 

Is there a way I could accomplish this, maybe some sort of namespacing (just guessing)?

Gametophyte answered 13/12, 2010 at 22:58 Comment(0)
G
467

Solution: Simply extract common attributes from both views and add them directly as children of the <resources> node:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="myattr1" format="string" />
    <attr name="myattr2" format="dimension" />

    <declare-styleable name="MyView1">
        <attr name="myattr1" />
        <attr name="myattr2" />
        ...
    </declare-styleable>

    <declare-styleable name="MyView2">
        <attr name="myattr1" />
        <attr name="myattr2" />
        ...
    </declare-styleable>
</resources>
Gametophyte answered 16/12, 2010 at 20:17 Comment(14)
what happens when myattr1 is string in MyView1 and integer in MyView2?Boothman
I don't think you can, but even if you could, I think these attribute names were a little misnamed :)Gametophyte
I don't think so, e.g. we can have 'orientation' attribute and for some view it is 'horizontal'/'vertical' and for other 'landscape'/'portrait'/'square'. From my point of view it's a bug (or at least inconsistent behavior) in Android (keep in mind that: 1. stylable attributes always start with prefix=view name and 2. if you create separate library projects for such views everything will work fine)Tret
Excellent, solved my Execution failed for task ':mergeDebugResources'. res/values/attrs.xml: Error: Found item Attr/myAttr more than one time. (Added to make this question better findable by Gradle users. :])Hankering
When I follow this answer I get ERROR: In <declare-styleable> com_app_view_widget, unable to find attribute customAttr For all the view I try to declare for. Any ideas?Tildatilde
@Dapp cleaned and rebuilt the project and that error message gone too.Selfknowledge
@Google: Crappy designMetage
@Boothman Just use <attr name="myattr1" format="string|integer" />. Works for me.Endothelium
@Endothelium Doing that you are losing xml field type validation by accepting 2 types when only 1 is supposed to be allowed.Declaration
@GlennBech exactly. Why we even need to declare stylable of a CustomView and put the possible attributes inside it, if it still can conflicted with other same-named attr under different stylables. Google seems overcomplicate things all over android development.Olszewski
This does cause an extra abstraction layer. On the other hand, it seems to help with consistent naming of attrs. When using lots of custom widgets, it's actually a nice feature. Subtle naming differences are hard to deal with when using a lot of custom attrs. E.g., picking between string_res_id or text_res_id when adding a custom view to a layout is frustrating.Uraninite
At first, this answer seemed not working but when I rebuilt the project, Tada! it is working like a charm.Brothers
why is this the accepted answer if it can't be referenced via code i.e. R.styleable.???_myattr1 or R.styleable.???_myattr2Footie
i cannot get value from attr xml, why does everyone voted it?Decker
T
73

I am posting this answer as the above-posted solution didn't work out for me in Android Studio. I need to share my custom attributes among my custom views so I tried the above solution in Android Studio but had no luck. So I experiment and go a way to do it. Hope it might help someone looking for the same problem.

  <?xml version="1.0" encoding="utf-8"?>
    <resources>
    <!-- parent styleable -->
     <declare-styleable name="MyView">
         <attr name="myattr1" format="string" />
         <attr name="myattr2" format="dimension" />
     </declare-styleable>

     <!-- inheriting parent styleable -->
     <!-- also note "myBackgroundColor" belongs to child styleable"MyView1"-->
    <declare-styleable name="MyView1" parent="MyView">
        <attr name="myattr1" />
        <attr name="myattr2" />
        <attr name="myBackgroundColor" format="color"/>
    </declare-styleable>


    <!-- inheriting parent styleable -->
    <!-- same way here "myfonnt" belongs to child styelable "MyView2" -->
    <declare-styleable name="MyView2" parent="MyView">
        <attr name="myattr1" />
        <attr name="myattr2" />
        <attr name="myfont" format="string"/>
        ...
    </declare-styleable>
</resources>

This works for me completely. We need to make a Parent styleable and then we need to inherit that parent styleable. For example, as I have done above : Parent styleable name MyView and inherited this to my other styleable like MyView1 and MyView2 respectively.

Tachycardia answered 12/10, 2015 at 9:18 Comment(6)
This worked for me. I couldn't find a way to reference the extracted attributes in code from the accepted answer.Creek
Hmm..that's weird.. the accepted solution seems to be working well for me (targetSdkVersion 27). Maybe because attributes like "text" is common & may have existed in some other attrs.xml..?Benignant
I tried with a name that's most probably uncommon & the accepted solution still worked for me.Benignant
I agree with the first comment! There is no way to reference an extracted attr from typedArray. Therefore you need to define a styleable parentProlix
for this to work don't forget to address this attribute in parent and not in child (for class MyView2 right: R.styleable.MyView2_myattr1, wrong: R.styleable.MyView_myattr1)Seigel
and you don't really need to specify parent at all for this to workSeigel
M
33

As Priya Singhal answered, Android Studio requires the common attribute names to be defined within their own style name. They can't be at the root any more.

However, there are a couple other things to note (which is why I am also adding an answer):

  • The common styles don't need to be named the same thing as a view. (Thanks to this answer for pointing that out.)
  • You don't need to use inheritance with a parent.

Example

Here is what I did in a recent project that has two custom views that both share the same attributes. As long as the custom views still have the names for the attributes and don't include a format, I can still access them as normal from code.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- common attributes to all custom text based views -->

    <declare-styleable name="TextAttributes">
        <attr name="text" format="string"/>
        <attr name="textSize" format="dimension"/>
        <attr name="textColor" format="color"/>
        <attr name="gravity">
            <flag name="top" value="48" />
            <flag name="center" value="17" />
            <flag name="bottom" value="80" />
        </attr>
    </declare-styleable>

    <!-- custom text views -->

    <declare-styleable name="View1">
        <attr name="text"/>
        <attr name="textSize"/>
        <attr name="textColor"/>
        <attr name="gravity"/>
    </declare-styleable>

    <declare-styleable name="View2">
        <attr name="text"/>
        <attr name="textSize"/>
        <attr name="textColor"/>
        <attr name="gravity"/>
    </declare-styleable>

</resources>

Streamlined example

In fact, I don't even need to put the attributes under a custom name. As long as I define them (give them a format) for at least one custom view, I can use them anywhere (without the format). So this also works (and looks cleaner):

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="View1">
        <attr name="text" format="string"/>
        <attr name="textSize" format="dimension"/>
        <attr name="textColor" format="color"/>
        <attr name="gravity">
            <flag name="top" value="48" />
            <flag name="center" value="17" />
            <flag name="bottom" value="80" />
        </attr>
    </declare-styleable>

    <declare-styleable name="View2">
        <attr name="text"/>
        <attr name="textSize"/>
        <attr name="textColor"/>
        <attr name="gravity"/>
    </declare-styleable>

</resources>

For a large project, though, this could get messy and defining them at the top in a single location might be better (as recommended here).

My answered 18/2, 2017 at 9:5 Comment(4)
What's wrong with inheritance? I have custom view hierarchies who's associated styleables do not reflect this relationship, which can only be deduced in the associated style definitions by naming conventions and the specific items defined therein (noticing that a few belong to one styleable and a few to another). I'd rather make it explicit with the parent attribute but haven't seen many posts suggesting it's usage.Phonoscope
@samis, I haven't worked on this for a while, but I don't know anything wrong with using parent. I think I was just saying it wasn't required.My
It's not required, I just made another subclass wrapped around an additional attribute that I didn't want to put into the base class. I'm just using comments and naming conventions to indicate the separation.Phonoscope
The streamlined example seems to be what worked the best for me. Using parent just resulted in it returning the incorrect values for certain attributes. <MyView app:label="label" app:font="monospace"> results in getString(R.attr.MyView_label) == "monospace"Nutriment
A
10

Thanks Lewis I had the same problem , and your inheritance solution gave me the hint for doing it like below and it works fine.I just declared common attributes at the above and rewrite it in the body of style declaration again without formatting. I hope it helps someone

<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- common attributes -->
     <attr name="myattr1" format="string" />
     <attr name="myattr2" format="dimension" />

 <!-- also note "myBackgroundColor" belongs to child styleable"MyView1"-->
<declare-styleable name="MyView1" >
    <attr name="myattr1" />
    <attr name="myattr2" />
    <attr name="myBackgroundColor" format="color"/>
</declare-styleable>

<!-- same way here "myfonnt" belongs to child styelable "MyView2" -->
<declare-styleable name="MyView2" parent="MyView">
    <attr name="myattr1" />
    <attr name="myattr2" />
    <attr name="myfont" format="string"/>
    ...
</declare-styleable>

Aw answered 4/1, 2017 at 16:5 Comment(0)
N
1

Just in case someone still stuck with this problem after tried available solution. I stuck with add subtitle attribute with string format.

My solution is remove the format.

before:

<attr name="subtitle" format="string"/>

after:

<attr name="subtitle"/>

Numerology answered 9/8, 2016 at 10:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.