Antoine Marques
Antoine Marques

Reputation: 1389

Custom View style in a library : use theme attr reference

I've made a custom View in a library. I want my view's background to be a reference of a theme attribute. For example like this :

<style name="MyView">
    <item name="android:background">?attr/my_view_background</item>
</style>

This pattern is used by Android's framework in several places, for example for list dividers.

But being in a library, i don't want to make a custom theme, because this would force someone using the lib to extend this custom theme which a find prohibitive.
I would rather like that the user be able to set the attribute whatever theme he uses, but this means somewhere a default value has to be defined.

So the question is how to define a default value, without making a custom theme ?

Upvotes: 1

Views: 650

Answers (1)

Antoine Marques
Antoine Marques

Reputation: 1389

Here's how to make it : using third parameter of Context.obtainStyledAttributes(int, int[], int, int) inside MyView constructor :

public MyView(AttributeSet attrs, int defStyle) {

    TypedArray backgroundArray = getContext().obtainStyledAttributes(
        attrs,                                    // The attrs passed to the view
        new int[] { android.R.attr.background },  // I'm only interrested in getting the background
        R.attr.myViewBackground,                  // The user can pass a custom background using this theme attribute
        theme R.style.MyView                      // And that's the default style
    );
    setBackgroundDrawable(backgroundArray.getDrawable(0)); // At 0, there's the background attribute
    backgroundArray.recycle();
}

Upvotes: 1

Related Questions