How to get the? Attr / value programmatically
I'm trying to do some kind of custom view style and I'm having problems displaying the styled attributes from the theme correctly.
For example, I would like to get the theme's EditText Text Color.
Looking at the theme stack, you can see that my theme is using it for the EditText's styles:
<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 am I looking for, how do I get it? attr / editTextColor
(Aka, the value assigned by the theme for "android: editTextColor")
Searching through google, I found enough 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 sure I must be doing it wrong as it always shows up as black and not gray? Can anyone please help?
source to share
Have you tried this?
EDIT: This is my short answer if you want a complete answer.
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 use the 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 normal 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 this is the answer you want, but it might put you on the right track.
source to share