1. Simple example
(1). Define a Attrs.xml file under the Res/values file
<?xml version= "1.0" encoding= "Utf-8"?><resources> <declare-styleable name= "My" > < attr name= "Content" format= "string"/> <attr name= "BackColor" format= "Reference|color"/> </ Declare-styleable></resources>
(2). layout file Use
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools " xmlns:my=" Http://schemas.android.com/apk/res/com.example.xmpptest " android: Layout_width= "Match_parent" android:layout_height= "match_parent" android:orientation= "vertical" > <com.example.xmpptest.mytextview android:layout_width= "match_parent" android:layout_height= " Wrap_content " my:content=" MyColor "> </com.example.xmpptest.MyTextView></LinearLayout>
(3). Custom Control Settings
public class Mytextview extends TextView {public Mytextview (context context) {This (context, null);} Public Mytextview (context context, AttributeSet Attrs) {This (context, attrs, 0);} Public Mytextview (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle); TypedArray a = Context.obtainstyledattributes (Attrs, r.styleable.my); String str = a.getstring (r.styleable.my_content); SetText (str + "@@"); A.recycle ();}}
2. Other Notes
(1). In each attr defined, format should be the specified type, string/integer/dimension/reference (reference R file)/color/enum/boolean, multiple format can be separated using | Others are the same, instance enum
<declare-styleable name= "My" > <attr name= "Content" format= "string"/> <attr name= "BackColor" format= "Reference|color"/> <attr name= "Size" > <enum name= "fill_parent" value= "-1"/> <enum name= "Wrap_content" value= "-2"/> </attr></declare-styleable>
(2). Xml namespace rules in the layout file,xmlns:toolbar=http://schemas.android.com/apk/res/[packagename]
Android_declare-styleable_ Properties of custom controls