Saren Inden Saren Inden -4 years ago 81
Android Question

Custom attr get color returns invalid values

I have a custom view in which i want to set the color of a textview.

I have


<declare-styleable name="PropertyView">
<attr name="propertyTitle" format="string" localization="suggested" />
<attr name="showTitle" format="boolean" />
<attr name="propertyTextColor" format="color" />
<attr name="propertyTextSize" format="dimension" />

I set it in the layout file

propertyview:propertyTextColor="@color/textLight" />

And in my code I set it

TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.PropertyView, 0, 0);

showTitle = a.getBoolean(R.styleable.PropertyView_showTitle, false);
String title = a.getString(R.styleable.PropertyView_propertyTitle);
float textSize = a.getDimension(R.styleable.PropertyView_propertyTextSize, -1);
int color = a.getColor(R.styleable.PropertyView_propertyTextColor, -1);
textSize = textSize / getResources().getDisplayMetrics().scaledDensity;
if(BuildConfig.DEBUG) Log.e(getClass().getName(), "Color set to: " + color);

if(textSize >= 0) mTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
if(color != -1) mTitleTextView.setTextColor(color);


But color keeps returning -1.
I also tried to set color to #000
When i do that i get a value of -16777216

I also tried a.getInteger and a.getInt

Anyone experience with this problem or suggestions?

Solution, thanks to Alex Fu

getColor cannot handle references

It is working now with

ColorStateList color = a.getColorStateList(R.styleable.PropertyView_propertyTextColor);

Answer Source

You are using a reference to a color in your example, however according to your attrs.xml file, that property must be of a color type, not a reference. This is probably the reason why when you used a hex color code it worked, but using a reference returned -1.

If you do change the format to a reference, you should also change the method to retrieve it from a.getColor() to a.getColorStateList().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download