I have a custom view in which i want to set the color of a textview.
I have
attrs.xml
<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" />
</declare-styleable>
I set it in the layout file
<com.something.views.PropertyView
android:id="@+id/dwf_rAwayTeamTimePenaltyInput"
style="@style/mw"
propertyview:propertyTextSize="16sp"
propertyview:propertyTitle="@string/AwayTeam"
propertyview:showTitle="true"
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);
setShowTitle(showTitle);
setTitle(title);
if(textSize >= 0) mTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
if(color != -1) mTitleTextView.setTextColor(color);
a.recycle();
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);
mTitleTextView.setTextColor(color);
The is some sort of bug with
attrs
.The following works perfectly.
attrs.xml
YourView.java
Usage
If you want every types of color to work
#ff0000
@color/primary
@color/primaryWithStates
You need to define your property as both color and reference
Then you simply access the value using
getColorStateList
For advanced needs where you want to digest the
ColorStateList
yourselfcolors.defaultColor
getColorForState
The easiest way to extract a color is by doing
It returns the color if there is one for the current state, otherwise the default one
This last part should be placed in the
drawableStateChanged()
method to be notified every time the state changesYou 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()
toa.getColorStateList()
.