Android: Default attributes for custom views

Karakuri picture Karakuri · May 17, 2012 · Viewed 8.8k times · Source

I have a custom view that extends one of the framework classes. Most Views in Android have some default attributes defined for them (such as Button being clickable, which is set by android:clickable="true").

How do I provide application-wide defaults for my custom view?

Answer

Karakuri picture Karakuri · May 22, 2012

I solved my own problem thusly:

res/values/attrs.xml:

<resources>
    <attr name="customViewStyle" type="reference" />
</resources>

res/values/styles.xml:

<resources>
    <style name="AppTheme" parent="@android:style/Theme.Light">
        <item name="android:background">@drawable/bg_light</item>
        <item name="customViewStyle">@style/CustomView</item>
    </style>

    <style name="CustomView">
        <item name="android:clickable">true</item>
        <item name="android:focusable">true</item>
        <item name="android:focusableInTouchMode">true</item>
    </style>
</resources>

Then all you do is set the theme in the manifest to AppTheme. This also works with standard widgets using android:[widget]Style in place of customViewStyle in the definition of AppTheme.