Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Attributes in Android

I'm trying to create a custom attribute called Tag for all editable elements. I added the following to attrs.xml

<declare-styleable name="Spinner">     <attr name="tag" format="string" /> </declare-styleable>  <declare-styleable name="EditText">     <attr name="tag" format="string" /> </declare-styleable> 

I get an error saying "Attribute tag has already been defined" for the EditText. Is it not possible to create a custom attribute of the same name on different elements?

like image 631
Arun Avatar asked Dec 31 '10 06:12

Arun


People also ask

What are custom attributes?

Custom attributes. A custom attribute is a property that you can define to describe assets. Custom attributes extend the meaning of an asset beyond what you can define with the standard attributes. You can create a custom attribute and assign to it a value that is an integer, a range of integers, or a string.

What is attr file in Android?

The Attr interface represents an attribute in an Element object. Typically the allowable values for the attribute are defined in a schema associated with the document.

What is the name of the file which is used to declare custom attributes?

You can take a look at it here (attrs. xml). You can define attributes in the top <resources> element or inside of a <declare-styleable> element.


2 Answers

If you are going to use an attr in more than one place then put it in the root element inside the <resources> element like the following :

<resources>      <attr name="tag" format="string" />      <declare-styleable name="Spinner">         <attr name="tag" />     </declare-styleable>      <declare-styleable name="EditText">         <attr name="tag" />     </declare-styleable>  </resources> 

Now you can use the tag attribute in anywhere you want inside this xml file .

Hope That Helps.

like image 175
ninjasense Avatar answered Sep 30 '22 10:09

ninjasense


See if my detailed answer about custom attributes helps: Defining custom attrs

like image 20
Rich Schuler Avatar answered Sep 30 '22 09:09

Rich Schuler