Android自定义View实现很简单
继承View,重写构造函数、onDraw,(onMeasure)等函数。
如果自定义的View需要有自定义的属性,需要在values下建立attrs.xml。在其中定义你的属性。
在使用到自定义View的xml布局文件中需要加入xmlns:前缀="http://schemas.android.com/apk/res/你的自定义View所在的包路径".
在使用自定义属性的时候,使用前缀:属性名,如my:textColor="#FFFFFFF"。
实例:
view plain copy to clipboard print ?
- package demo.view.my;
- import android.content.Context;
- import android.content.res.TypedArray;
- import android.graphics.Canvas;
- import android.graphics.Color;
- import android.graphics.Paint;
- import android.graphics.Paint.Style;
- import android.util.AttributeSet;
- import android.view.View;
-
-
-
-
-
-
-
-
-
-
-
-
- public class MyView extends View {
-
- Paint mPaint;
- public MyView(Context context) {
- super(context);
-
- }
-
- public MyView(Context context, AttributeSet attrs){
- super(context, attrs);
- mPaint = new Paint();
-
-
-
- TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView);
- int textColor = array.getColor(R.styleable.MyView_textColor, 0XFF00FF00);
- float textSize = array.getDimension(R.styleable.MyView_textSize, 36);
- mPaint.setColor(textColor);
- mPaint.setTextSize(textSize);
-
- array.recycle();
- }
-
- public void onDraw(Canvas canvas){
- super.onDraw(canvas);
-
-
-
- mPaint.setStyle(Style.FILL);
- canvas.drawRect(10, 10, 100, 100, mPaint);
-
- mPaint.setColor(Color.BLUE);
- canvas.drawText("我是被画出来的", 10, 120, mPaint);
- }
- }
相应的属性文件:
view plain copy to clipboard print ?
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <declare-styleable name="MyView">
- <attr name="textColor" format="color"/>
- <attr name="textSize" format="dimension"/>
- </declare-styleable>
- </resources>
在布局文件中的使用:
view plain copy to clipboard print ?
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:my="http://schemas.android.com/apk/res/demo.view.my"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
-
- <demo.view.my.MyView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- my:textColor="#FFFFFFFF"
- my:textSize="22dp"
- />
- </LinearLayout>
//定义一个矩形
RectF rf1 = new RectF(10, 130, 110, 230);
//画弧顺时针
canvas.drawArc(rf1, 0, 45, true, paint);
//画线
canvas.drawLine(150, 10, 250, 110, paint);
//定义一个矩形
RectF rf2 = new RectF(150, 130, 250, 230);
//画圆
canvas.drawOval(rf2, paint);