I'm trying to do some custom view styling and I'm having trouble correctly picking up styled attributes from the theme.
For instance, I would like to get the themes EditText's Text Colour.
Looking through the theme stack you can see my theme uses this to style it's EditText's:
<style name="Base.V7.Widget.AppCompat.EditText" parent="android:Widget.EditText">
<item name="android:background">?attr/editTextBackground</item>
<item name="android:textColor">?attr/editTextColor</item>
<item name="android:textAppearance">?android:attr/textAppearanceMediumInverse</item>
</style>
What I'm looking for, is how do I get that ?attr/editTextColor
(Aka, the value assigned by the theme to "android:editTextColor")
Searching through google, I have found enough of this answer:
TypedArray a = mView.getContext().getTheme().obtainStyledAttributes(R.style.editTextStyle, new int[] {R.attr.editTextColor});
int color = a.getResourceId(0, 0);
a.recycle();
But I'm pretty sure I must be doing this wrong as it always displays as black rather than grey?
The Attr interface represents an attribute in an Element object. Typically the allowable values for the attribute are defined in a schema associated with the document.
As commented from @pskink:
TypedValue value = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.editTextColor, value, true);
getView().setBackgroundColor(value.data);
will pull the attribute from the theme currently assigned to the context.
Thanks @pskink!
Have you tried this ?
EDIT : This is my short answer if you want a complete answer ask me
Your attrs.xml file :
<resources>
<declare-styleable name="yourAttrs">
<attr name="yourBestColor" format="color"/>
</declare-styleable>
</resources>
EDIT 2 : Sorry I forgot to show how I'm using my attr value in layout.xml, so :
<com.custom.coolEditext
android:id="@+id/superEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:yourBestColor="@color/any_color"/>
and then in your custom Editext :
TypedArray a = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.yourAttrs, 0, 0);
try {
int colorResource = a.getColor(R.styleable.yourAttrs_yourBestColor, /*default color*/ 0);
} finally {
a.recycle();
}
I'm not sure if it is the answer what you want but it can put you on good way
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With