Android: how do I define an attribute for a custom widget?
Looking at Mark Murphy's excellent example at http://github.com/commonsguy/cw-advandroid/tree/master/Views/ColorMixer/ you can see where he's defined a custom widget called ColorMixer. ColorMixer has an attribute named "initialColor" declared in attrs.xml.
In the constructor for ColorMixer, he obtains the attribute value as follows:
TypedArray a=getContext()
.obtainStyledAttribu开发者_StackOverflowtes(attrs, R.styleable.ColorMixer, 0, 0);
color = a.getInt(R.styleable.ColorMixer_initialColor, 0xFFA4C639);
a.recycle();
This works just fine if 'R' is available to ColorMixer. This will be the case if ColorMixer is written for and compiled with whatever package it's going to be part of.
But what if I wanted ColorMixer to be more generally useful? I want to use the same source, unmodified, or even maybe put it into a jar file. This means you can't make references to 'R'.
It seems to me that I should be able to do something like
TypedArray a=getContext()
.obtainStyledAttributes(attrs, what-do-I-do-here?, 0, 0);
int resid = context.getResources().getIdentifier("ColorMixer_initialColor",
"attr", "com.commonsware.android.colormixer.ColorMixer")
color = a.getInt(resid, 0xFFA4C639);
but getIdentifier never returns anything but zero. Is there something more I should be doing? I want to re-write this code to be completely independent of 'R'
For source code to a concrete example, see www.efalk.org/tmp/CustomWidget.tar.gz
Looking at Mark Murphy's excellent example
:: blushes ::
Thanks!
But what if I wanted ColorMixer to be more generally useful?
You mean like this?
I want to use the same source, unmodified, or even maybe put it into a jar file. This means you can't make references to 'R'.
And that is precisely why I've started the Android Parcel Project, within the past few hours as it turns out.
The problem is two-fold: getting the identifier from a string representation, and ensuring this stuff won't collide with other reusable widgets. Plus, you need to deploy those resources, which can't just be tucked in the JAR. And so on.
I have some helper code (also available in parcel form) that will handle the resource ID stuff. Documentation is light but will improve over the course of the week.
If you have additional questions about how the engineering of all this works, join the cw-android Google Group and chime in there!
精彩评论