Basic steps for customizing properties in Android
This time it's just the simplest custom attribute flow.
1. Create a resource file: Resources/attr.xml
<?xml version= "1.0" encoding= "Utf-8"?><resources> <declare-styleable name="Test"> <attr name="Test" format="string" /> <attr name="Testarr" format="integer" /> </declare-styleable></Resources>
2. Custom View class
Public class mytextview extends View{ Private Static FinalString TAG ="Mytextview"; Public Mytextview(context context, AttributeSet attrs) {Super(context, attrs); TypedArray ta = context.obtainstyledattributes (attrs,r.styleable.test); String Text = ta.getstring (R.styleable.test_testarr);intTextattr = Ta.getinteger (R.styleable.test_text,-1); LOG.E (TAG,"Text:"+text+", textattr:"+TEXTATTR); Ta.recycle (); }}
3. Using in the layout file
<?xml version= "1.0" encoding= "Utf-8"?><relativelayout xmlns: Android = "http://schemas.android.com/apk/res/android" xmlns:tools =" Http://schemas.android.com/tools " XMLNS:YXM = "Http://schemas.android.com/apk/res-auto" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = "org.xm.customview.MainActivity" <org.xm.customview.MyTextViewandroid:layout_width="100DP"android:layout_ Height="200DP"yxm:testarr="yxm:text" = "xiaoming" /> </relativelayout>
Attention
use in Androidstudio: xmlns:yxm="http://schemas.android.com/apk/res-auto" automatically import named Controls
If you want to use the completed package name in Eclipse, such xmlns:sdf="http://schemas.android.com/apk/res/org.xm.customview" as:
Add a parameter to a custom attribute using a defined namespace, for example:yxm:testArr="20"
4. Implement a custom view to get custom properties
Public class mytextview extends View{ Private Static FinalString TAG ="Mytextview"; Public Mytextview(context context, AttributeSet attrs) {Super(context, attrs); TypedArray ta = context.obtainstyledattributes (attrs,r.styleable.test); String Text = ta.getstring (r.styleable.test_text);intTextattr = Ta.getinteger (R.styleable.test_testarr,-1); LOG.E (TAG,"Text:"+text+", textattr:"+TEXTATTR); Ta.recycle (); }}
Attention
R.styleable.test_textThe Text_ is automatically added (must be written) and then the property name is added to the text
So the end will print:text:xiaoming,textattr:20, or very simple!
Basic steps for customizing properties in Android