Android开发总结笔记 自定义View的编写 3-8

来源:互联网 发布:外置式网络打印服务器 编辑:程序博客网 时间:2024/06/06 17:12

自定义View的实现方式有三种

  • 自绘控件 继承于View实现的控件

  • 组合控件    继承于布局实现的View

  • 继承控件    继承于系统原有控件实现的View



自定义控件主要是使用Path.Paint.Canvas这三个绘图类来对控件进行绘制。这里只记录一下自绘控件

自绘控件

首先要在资源文件的<declare-styleable>里面定义一些需要的属性,这些属性可以在xml中改变(不需要可以定义)一般在values/attrs.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3.    <declare-styleable name="myview">
  4.        <attr name="mycolor" format="color"/>
  5.        <attr name="mysize" format="dimension"/>
  6.        <attr name="mytext" format="string"/>
  7.    </declare-styleable>
  8. </resources>

然后根据这些属性编写一个简单的View

  1. public class MyView extends View {
  2.    private Paint mPaint;
  3.    private final String text;
  4.    public MyView(Context context, AttributeSet attrs) {
  5.        super(context, attrs);
  6.        mPaint = new Paint();
  7.        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.myview);//获取属性集
  8.        int color = array.getColor(R.styleable.myview_mycolor, 0x000001);
  9.        float size=array.getDimension(R.styleable.myview_mysize,15f);
  10.        text = array.getString(R.styleable.myview_mytext);
  11.        mPaint.setColor(color);
  12.        mPaint.setTextSize(size);
  13.        array.recycle();//一定要调用,否则这次设定会对下次设定产生影响
  14.    }
  15.    @Override
  16.    protected void onDraw(Canvas canvas) {
  17.        super.onDraw(canvas);
  18.        canvas.drawText(text,10,120,mPaint);
  19.    }
  20. }


应用到布局文件中去,要注意命名空间,gradle项目可以自动识别,所以不用写包名

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2.    xmlns:myview="http://schemas.android.com/apk/res-auto"
  3.    android:layout_width="match_parent"
  4.    android:layout_height="match_parent">
  5.    <com.example.wenkchan.pratice.MyView
  6.        android:layout_width="wrap_content"
  7.        android:layout_height="wrap_content"
  8.        myview:mycolor="@color/colorAccent"
  9.        myview:mysize="20dp"
  10.        myview:mytext="哈哈" />
  11. </RelativeLayout>


好了,基本的就是这么简单

0 0
原创粉丝点击