Android-------------自定义View

来源:互联网 发布:php mt_rand 编辑:程序博客网 时间:2024/09/21 09:18

1.创建一个自定义的view的类

public class Myview extends View {   private Paint mpaint;    public Myview(Context context) {        this(context,null);    }    public Myview(Context context, AttributeSet attrs) {        this(context, attrs,0);    }    public Myview(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        //初始化画笔        mpaint=new Paint();        mpaint.setAntiAlias(true);//设置平滑度    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        //设置画笔的颜色        mpaint.setColor(Color.BLUE);        //画正方形前两个参数为矩形左上角的坐标,后两个参数为右下角的坐标        canvas.drawRect(0,0,100,100,mpaint);        mpaint.setColor(Color.YELLOW);        //前两个参数为圆心的坐标,100为圆的半径,mpaint表示画笔       canvas.drawCircle(200,200,100,mpaint);    }}

2.在res-layout下

?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"   ><-这里一定导入自定义view的包名.类名-><com.weewe.Myview    android:layout_width="wrap_content"    android:layout_height="wrap_content" /></RelativeLayout>

效果展示: