Android: Default attributes for custom views

青春壹個敷衍的年華 提交于 2019-12-04 19:00:36

问题


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?


回答1:


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.




回答2:


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




回答3:


I think you will need to override the View constructors that take an AttributeSet argument, and build your own modified AttributeSet to pass to the superclass constructor.

EDIT: Even easeer, just have your View subclass constructor call setClickable etc to change the defaults to what you want.



来源:https://stackoverflow.com/questions/10640668/android-default-attributes-for-custom-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!