Skip to content Skip to sidebar Skip to footer

Editing An Attributeset In Android?

Is there a way to add or remove keys from an AttributeSet when defining a custom View? public BFPlayer(Context context, AttributeSet attrs, int defStyle) { super(contex

Solution 1:

After a lot of experimentation, reading the Android source code, and Googling, my suspicions were confirmed when I found this post to a similar question

Even though it looks like Android is parsing an XML file to build the layout for your app, the XML is actually processed as build time and converted to an optimized class which is loaded. Modifying attributes on the fly (such as via a facade) would circumvent the performance gains from this build-time compilation of views. Therefore it can't be done. Whatever is in the XML at compile time, that's what your class will see in the AttributeSet at run time.

Specifically, XML files are compiled to a binary representation which is parsed by XmlBlock - a private class of android.content.res which is not exposed for subclassing.

It may be possible to subclass XmlBlock by using Reflection (since Reflection bypasses a lot of checks and balances, allowing you to access private members and methods) - but I'm not very knowledgeable about using Reflection and I think it's an anti-pattern, anyway.

Still, if someone knows a way to subclass a package-private class using Reflection and can post how, I would gladly accept it as the answer (since it's the only way to accomplish what I want)

Post a Comment for "Editing An Attributeset In Android?"