Featured post
android - How to: Define theme (style) item for custom widget -
i've written custom widget control use throughout our application. widget class derives imagebutton
, extends in couple of simple ways. i've defined style can apply widget it's used, i'd prefer set through theme. in r.styleable
see widget style attributes imagebuttonstyle
, textviewstyle
. there way create custom widget wrote?
yes, there's 1 way:
suppose have declaration of attributes widget (in attrs.xml
):
<declare-styleable name="customimagebutton"> <attr name="customattr" format="string"/> </declare-styleable>
declare attribute use style reference (in attrs.xml
):
<declare-styleable name="customtheme"> <attr name="customimagebuttonstyle" format="reference"/> </declare-styleable>
declare set of default attribute values widget (in styles.xml
):
<style name="widget.imagebutton.custom" parent="android:style/widget.imagebutton"> <item name="customattr">some value</item> </style>
declare custom theme (in themes.xml
):
<style name="theme.custom" parent="@android:style/theme"> <item name="customimagebuttonstyle">@style/widget.imagebutton.custom</item> </style>
use attribute third argument in 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(); } }
now have apply theme.custom
activities use customimagebutton
(in androidmanifest.xml):
<activity android:name=".myactivity" android:theme="@style/theme.custom"/>
that's all. customimagebutton
tries load default attribute values customimagebuttonstyle
attribute of current theme. if no such attribute found in theme or attribute's value @null
final argument obtainstyledattributes
used: widget.imagebutton.custom
in case.
you can change names of instances , files (except androidmanifest.xml
) better use android naming convention.
- Get link
- X
- Other Apps
Comments
Post a Comment