自定义属性 view

首先自定义一个圆,相信以前的学习大家都会画圆,在values下写一些自定义的属性

package com.exaple.day01rikao;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class Myview extends View {
int radius;
int color;
private final static String Nam = "chen";

public Myview(Context context, AttributeSet attrs) {
super(context, attrs);
/*
* TypedArray ta = context.obtainStyledAttributes(attrs,
* R.styleable.Myview); radius = ta.getInt(R.styleable.Myview_radius,
* 0); color = ta.getInt(R.styleable.Myview_mycolor, 0);

较难的一种方式
*/
radius = attrs.getAttributeIntValue(Nam, "radius", 0);
color = attrs.getAttributeIntValue(Nam, "mycolor", 0);

简单的一中方式
}

@Override
protected void onDraw(Canvas canvas) {
Paint pa = new Paint();
Paint pa1 = new Paint();
float wi = canvas.getWidth();
float he = canvas.getHeight();
pa.setColor(color);
pa1.setColor(Color.WHITE);

canvas.drawColor(Color.WHITE);
canvas.drawCircle(wi / 2, he / 2, radius, pa);
/* canvas.drawCircle(wi / 2, he / 2, 55, pa1); */
/* canvas.drawText("hhhhhhhhhhhhhh", wi / 4, he / 4, pa); */
super.onDraw(canvas);
}

/*
* @Override public boolean onTouchEvent(MotionEvent event) { wi =
* event.getX(); he = event.getY(); this.invalidate();
*
* return true; }
*/

}

在values 下面新建一个attrs文件

<?xml version="1.0" encoding="utf-8"?>
<resources>

<declare-styleable name="Myview">-----类名
<attr name="radius" format="integer"></attr>
<attr name="mycolor" format="color|reference"></attr>
</declare-styleable>

</resources>

 Mainactivity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:fan="chen"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<com.exaple.day01rikao.Myview
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fan:mycolor="#f00"
fan:radius="100" />

</RelativeLayout>

原文地址:https://www.cnblogs.com/jsonfan/p/5371978.html