For a long time did not update the blog, would like to accumulate a bit of depth of things hair, but has not found a very good point. So, write something basic, just accumulate it. Custom components are inevitably used in Android development, with ImageButton as an example of how to customize a component and its properties:
The first step, custom properties for the component in Values/attrs.xml: <?xml version= "1.0" encoding= "Utf-8"?><resources> < Declare-styleable name= "custombtn" > <attr name= "Text" format= "string"/> <attr name= "TextColor" f ormat= "Color"/> <attr name= "textSize" format= "Dimension"/> </DECLARE-STYLEABLE></RESOURCES&G T
The second step, rewrite ImageButton class: public class Custombtn extends imagebutton{private paint paint, private String text; Public custombtn (context context, AttributeSet Attrs) {Super (context, attrs); Paint=new Paint (); TypedArray typearray=context.obtainstyledattributes (ATTRS,R.STYLEABLE.CUSTOMBTN); int Color=typearray.getcolor (r.styleable.custombtn_textcolor,color.white); Float textsize=typearray.getdimension (r.styleable.custombtn_textsize,20); Text=typearray.getstring (R.styleable.custombtn_text); Paint.settextalign (Align.center); Paint.setcolor (color); Paint.settextsize (textSize); Typearray.recycle (); } @Override protected void OnDraw (canvas canvas) {super.ondraw (canvas); Canvas.drawtext (Text,canvas.getwidth ()/2,canvas.getheight ()/2, paint); }}
Step three, use CUSTOMBTN in the layout file: The package name in Xmlns:custombtn in Androidmanifest.xml <?xml version= "1.0" encoding= "Utf-8"?>< Relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:custombtn= "http// Schemas.android.com/apk/res/com.yeahis.shuyudragstore "xmlns:tools=" Http://schemas.android.com/tools "Android: Layout_width= "Match_parent" android:layout_height= "@dimen/market_category_height" android:background= "@drawable/ Mall_category_item "><com.yeahis.shuyudragstore.widget.custombtnandroid:id=" @+id/mall_category_btn " Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_alignparenttop= "true" Android:layout_alignparentleft= "true" android:background= "@android: Color/transparent" android:src= "@drawable/ Mall_category_title "custombtn:text=" @string/mall_category_title "custombtn:textcolor=" @android: Color/black " Custombtn:textsize= "15SP"/></relativelayout>
Custom components and their properties in Android