I can create custom attributes and apply them to regular EditTexts
, like this:
<EditText
android:id="@+id/field1"
custom:attr1="whatever"
(...)
<EditText
android:id="@+id/field2"
custom:attr1="whatever2"
(...)
My question: can I read the value of those custom attributes without creating a class that extends EditText
? I mean, I want to read custom attributes from my Activity
, but the examples I see so far requires me to read the values from the constructor of a custom view, like here: Defining custom attrs
I'd say no, you can't. I checked sources of
EditText
and it parents and didn't found place where it stores custom atributes to instance property so you can use them later. So I think you need to create your own class that extendsEditText
.Yes, you can get those attributes without extending the classes. For this you could use a special
Factory
set on theLayoutInflater
that theActivity
will use to parse the layout files. Something like this:where the
CustomAttrFactory
is like this:The idea comes from a blog post, you may want to read it for additional information.
Also, depending on that custom attribute(or attributes if you have other) you could just use
android:tag="whatever"
to pass the additional data(and later retrieve it in theActivity
withview.getTag()
).I would advise you to not use those custom attributes and rethink your current approach.