Graeme
Graeme

Reputation: 25864

How to get an ?attr/ value programmatically

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?

Upvotes: 9

Views: 12892

Answers (2)

Graeme
Graeme

Reputation: 25864

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!

Upvotes: 20

MrLeblond
MrLeblond

Reputation: 1035

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

Upvotes: 4

Related Questions