第一种
/MainActivity/res/values/attrs.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyCircle"> <attr name="radius" format="integer"/> <attr name="mycolor" format="reference|color"/> </declare-styleable> </resources> |
|
/MainActivity/src/com/ch/myviews/MyCircle.java
package com.ch.myviews; import com.ch.myviewattr.R; import android.content.Context; public class MyCircle extends View { public MyCircle(Context context, AttributeSet attrs) { } // canvas.drawColor(Color.BLACK); } |
/MainActivity/res/layout/activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:myattr="http://schemas.android.com/apk/res/com.ch.myviewattr" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <com.ch.myviews.MyCircle </RelativeLayout> |
第二种
/MainActivity/res/values/attrs.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyCircle"> <attr name="radius" format="integer"/> <attr name="mycolor" format="reference|color"/> </declare-styleable> </resources> |
/MainActivity/src/com/ch/myviews/MyCircle.java
package com.ch.myviews; import com.ch.myviewattr.R; import android.content.Context; public class MyCircle extends View { radius = attrs.getAttributeIntValue(NAMESPACE, "radius", 0); // canvas.drawColor(Color.BLACK); } |
/MainActivity/res/layout/activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:myattr="aaa1407a" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <com.ch.myviews.MyCircle </RelativeLayout> |