Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Default attributes for custom views

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?

like image 860
Karakuri Avatar asked May 17 '12 17:05

Karakuri


People also ask

What is the name of the file which is used to declare custom attributes?

What is the name of the file which is used to declare custom attributes? Create an XML res/values/attrs. xml file to define new attributes alongwith their data type.

What are the types of custom views?

In Android, there are actually two other Views readily available to do this: Spinner and AutoCompleteTextView , but regardless, the concept of a Combo Box makes an easy-to-understand example.


2 Answers

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.

like image 59
Karakuri Avatar answered Oct 30 '22 12:10

Karakuri


You could additionally create a style for this layout and set the style where you use the view.

source: http://developer.android.com/guide/topics/resources/style-resource.html

like image 23
soost Avatar answered Oct 30 '22 12:10

soost