I've begun playing around with styles and such in my android applications, and I have gotten everything working so far. I quite understood the 'style' section of the guide.
But, looking around, as in this thread, I can't really figure out the difference between the two (declare-stylable
and style
).
From my understanding declare-styleable
takes the attribute specified in it and specifies it as styleable, and then from the code one changes it as he wants.
But if this is what it really does, wouldn't it be simpler to just define the attribute in the layout? Or declare a style specifying it?
Check this thread.
Without the
declare-styleable
it would not be possible to create a new custom drawable state.I think there is only the following difference between declaring an attribute as styleable or not.
In attrs.xml you can declare custom attributes, either directly within the "resources" section or within "declare-styleable":
So now we defined "attrib1" as non-styleable and "attrib2" as styleable.
In
layout/someactivity.xml
we can use these attributes directly (no namespace needed):You can use the "styleable" attribute "attrib2" within a
style.xml
declaration. Again, no namespace is needed here (even if a namespace was used in the layout XML).Then you can also set the attributes per style.
Let us assume that we do this: we set
attrib1
directly in XML, and we setattrib2
in a style.Elsewhere I have seen descriptions stating that "
blahblah
" must be the name of the custom view class that uses these attributes, and that you need to use a namespace to refer to your custom attributes in the layout XML. But none of this seems to be necessary.The difference between styleable and non-styleable seems to be that:
style.xml
" declarations.obtainStyledAttributes()
, and the non-styled attributes withattr.getAttributeValue()
or similar.In most tutorials and examples I've seen on the Web, only the
obtainStyledAttributes()
was used. However, this does not work with attributes declared directly in layout, without using a style. If you doobtainStyledAttributes()
as shown in most tutorials, you will not get the attributeattrib1
at all; you will only getattrib2
since it was declared in the style. The direct method usingattr.getAttributeValue()
works:Since we used no namespace to declare "
attrib1
", we passnull
as the namespace argument ingetAttributeValue()
.