Skip to content

Instantly share code, notes, and snippets.

@oksep
Created February 24, 2016 02:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oksep/ea6e70703b6fbcc28420 to your computer and use it in GitHub Desktop.
Save oksep/ea6e70703b6fbcc28420 to your computer and use it in GitHub Desktop.
Define your custom widget theme

Define your custom widget theme:

1.Suppose you have a declaration of attributes for your widget (in attrs.xml):

<declare-styleable name="CustomImageButton">
    <attr name="customAttr" format="string"/>
</declare-styleable>

2.Declare an attribute you will use for a style reference (in attrs.xml):

<declare-styleable name="CustomTheme">
    <attr name="customImageButtonStyle" format="reference"/>
</declare-styleable>

3.Declare a set of default attribute values for the widget (in styles.xml):

<style name="Widget.ImageButton.Custom" parent="android:style/Widget.ImageButton">
    <item name="customAttr">some value</item>
</style>

4.Declare a custom theme (in themes.xml):

<style name="Theme.Custom" parent="@android:style/Theme">
    <item name="customImageButtonStyle">@style/Widget.ImageButton.Custom</item>
</style>

5.Use this attribute as the third argument in your widget's constructor (in CustomImageButton.java):

public class CustomImageButton extends ImageButton {
    private String customAttr;

    public CustomImageButton( Context context ) {
        this( context, null );
    }

    public CustomImageButton( Context context, AttributeSet attrs ) {
        this( context, attrs, R.attr.customImageButtonStyle );
    }

    public CustomImageButton( Context context, AttributeSet attrs,
            int defStyle ) {
        super( context, attrs, defStyle );

        final TypedArray array = context.obtainStyledAttributes( attrs,
            R.styleable.CustomImageButton, defStyle,
            R.style.Widget_ImageButton_Custom ); // see below
        this.customAttr =
            array.getString( R.styleable.CustomImageButton_customAttr, "" );
        array.recycle();
    }
}

6.Now you have to apply Theme.Custom to all activities that use CustomImageButton (in AndroidManifest.xml):

<activity android:name=".MyActivity" android:theme="@style/Theme.Custom"/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment