方法一:
MyView.class
package com.bwie.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; public class MyView extends View { private int radius; private final static String NAMESPACE = "aaa1407a"; public MyView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub radius = attrs.getAttributeIntValue(NAMESPACE, "radius", 0); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); Paint paint=new Paint(); paint.setColor(Color.CYAN); canvas.drawCircle(getWidth()/2, getHeight()/2, radius, paint); } }
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.bwie.view.MyView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" myattr:radius="200" /> </RelativeLayout>
attrs
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyView"> <attr name="radius" format="integer"/> <attr name="mycolor" format="reference|color"/> </declare-styleable> </resources>
方法二:
MyView.class
package com.bwie.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; public class MyView extends View { private int radius; public MyView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub
//获得自定义的属性,即获得自定义的半径 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView); radius=a.getInt(R.styleable.MyView_radius, 0); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); Paint paint=new Paint(); paint.setColor(Color.CYAN); canvas.drawCircle(getWidth()/2, getHeight()/2, radius, paint); } }
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.bwie.test"//主包名 android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <com.bwie.view.MyView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" myattr:radius="200" /> </RelativeLayout>
attrs
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyView"> <attr name="radius" format="integer"/> <attr name="mycolor" format="reference|color"/> </declare-styleable> </resources>
时间: 2024-09-29 14:20:31