自定义view快速入门--基础概念

来源:互联网 发布:淘宝店家虚假发货 编辑:程序博客网 时间:2024/05/17 18:29

  对于自定义view一直都处于模模糊糊的状态,在这短暂的寒假里,索性买了《Android开发艺术探索》和《Android群英传》,沉下心来,吃透自定义。

三种自定义view的方式

 1. 扩张现有的view,即继承现有的view,添加新的功能。 2. 自定义viewgroup,将现有的view集成起来,并添加一些新的属性或者功能。 3. 继承view 这个基类,属于创造一个新的控件的过程。

自定义view时,重写的方法

 1. onMeasure()                   测量view的大小 2. onDraw()                      绘制图形,文字等 3. onLayout()                    确定view的位置 4. onTouchEvent()                处理各种事件

以下为四个方法的参数详解

onMeasure()

先上代码,随便浏览一下,有个大概的印象就行。(以下代码可以当作模版代码,再次使用时,基本不用修改)

    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        super.onMeasure(widthMeasureSpec, heightMeasureSpec);        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);        int widthResult = 0;        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);        int heightResult = 0;        if (widthSpecMode == MeasureSpec.EXACTLY) {            widthResult = widthSpecSize;        } else {            widthResult = 200;            if (widthSpecMode == MeasureSpec.AT_MOST) {                widthResult = Math.min(widthResult, widthSpecSize);            }        }        if (heightSpecMode == MeasureSpec.EXACTLY) {            heightResult = heightSpecSize;        } else {            heightResult = 200;            if (widthSpecMode == MeasureSpec.AT_MOST) {                heightResult = Math.min(heightResult, heightSpecSize);            }        }        setMeasuredDimension(widthResult, heightResult);    }

MeasureSpec是一个32位的int值,它的高2位代表测量模式,剩下的代表测量的数值。通常情况下我们为了表示两个信息,一般会用两个变量分别来表示,这里为了减少内存的消耗,将他们合并成一个对象。当然,系统也给出了相应的解析方法,如下面的代码:

MeasureSpec.getMode(heightMeasureSpec)  获取测量模式MeasureSpec.getSize(heightMeasureSpec)  获取测量数值

说了那么多次测量模式,那么测量模式是什么鬼呢?
进入MeasureSpec类查看,可以看到如下三种模式:

  1. EXACTLY
  2. AT_MOST
  3. UNSPECIFIED

如果你英语还行的话,可以大概猜出意思来。(前面部分为直接翻译,后面部分为解释)

  1. 精确模式,你在xml中设置参数是多少,就会获取响应的值。
  2. 尽可能多,在父类容器允许的情况下,尽可能多
  3. 不确切的,父容器不对view进行限制,要多大就有多大,一般很少用。

    关于这三个测量模式的具体讲解将在下一篇中解释,这里先有个基础的了解。

onDraw()

先上代码,有个基本印象:

    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        mWidth = getWidth();        mHeight = getHeight();        canvas.drawCircle(mWidth / 2, mHeight / 2, mWidth / 2, mPaint);        invalidate();    }

Canvas 画布,所有的图像信息都上在Canvas中显示的。

小知识:invalidate()与postInvalidate()的区别
invalidate()用于刷新UI,在 main thread 中使用,即UI线程
postInvalidate() 用于刷新UI,但是它在 worker thread 中使用,即非UI线程

onLayout()

上代码

    @Override    protected void onLayout(boolean changed, int l, int t, int r, int b) {    }

lef,top,right,bottom, 左,上,右,底,
onLayout() 一般在自定义viewgroup的时候才要用到, 为了确定子view的位置。

onTouchEvent()

上代码:

    @Override    public boolean onTouchEvent(MotionEvent event) {        switch (event.getAction()) {            case MotionEvent.ACTION_DOWN:                mLastX = (int) event.getX();                mLastY = (int) event.getY();                break;            case MotionEvent.ACTION_MOVE:                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)getLayoutParams();                params.leftMargin = getLeft() + dx;                params.topMargin = getTop() + dy;                setLayoutParams(params);                break;            case MotionEvent.ACTION_UP:                break;        }        invalidate();        return true;    }

MotionEvent中封装了一些常量,它定义了触控事件的类型。常见的有如下:

  1. MotionEvent.ACTION_DOWN
  2. MotionEvent.ACTION_MOVE
  3. MotionEvent.ACTION_UP

分别是 1,手指按下屏幕 2,在屏幕中移动 3,手指抬起  三个动作。
view自身提供一下方法,都是view相对于父容器来获取的。

getLeft() 获取view到父容器左边的距离

getRight() 获取view到父容器右边的距离

getTop() 获取view到父容器上边的距离

getBottom() 获取view到父容器底部的距离

MotionEvent提供以下方法,都是触控点相对于view来获取的

getX() 获取触控点到view左边的距离

getY()

getRawX() 获取触控点到屏幕左边的距离

getRawY()

小实例

基础概念如是,下面来一个简单的例子,体验一下自定义。
需求描述:自定义一个字符串属性,设置该属性之后,将字符串显示在view中,添加点击事件,点击之后改变字符串,变成一个随机数。

  1. 首先我们在继承Textview的基础上进行自定义,新的View命名为AddTextView。然后,在valus目录下新建attrs.xml,里面的内容如下:
<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="MyString">        <attr name="myTitle" format="string"/>    </declare-styleable></resources>

声明styleable,name属性为MyString,name属性为后期调用这个styleable而准备,有点像id的作用。
声明attr标签,name属性为myTitle,格式format为字符串,myTitle为后期在xml中调用的属性名,例如:TextView中的text属性,format为字符串或者引用资源。
2. 在view的两个参数的构造方法中获取xml中声明的属性值,因为默认是通过两个参数的构造方法获取的:

    public AddTextView(Context context, AttributeSet attrs) {        super(context, attrs);        num= 0;        translateNum=0;        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyString);        mTitle = ta.getString(R.styleable.MyString_myTitle);        setText(mTitle);        setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                int num = (int) (Math.random()*10);                setText(String.valueOf(num));            }        });    }

TypedArray 用于保存从xml中获取到的属性数组,R.styleable.MyString则为第一步中声明的styleable,这里通过name获取到相应的数据。

那么,整个AddTextView的代码是这样的:

import android.content.Context;import android.content.res.TypedArray;import android.graphics.LinearGradient;import android.os.Handler;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;import android.widget.TextView;/** * Created by zone on 2017/1/22. */public class AddTextView extends TextView {    private String mTitle;    public AddTextView(Context context) {        super(context);    }    public AddTextView(Context context, AttributeSet attrs) {        super(context, attrs);        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyString);        mTitle = ta.getString(R.styleable.MyString_myTitle);        setText(mTitle);        setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                int num = (int) (Math.random()*10);                setText(String.valueOf(num));            }        });    }    public AddTextView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }}
<?xml version="1.0" encoding="utf-8"?><LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:custom="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.zone.custonview.MainActivity">    <com.zone.custonview.AddTextView        android:id="@+id/mytextview"        android:layout_width="120px"        android:layout_height="120px"        android:layout_below="@+id/topbar"        android:gravity="center"        android:textSize="20dp"        android:background="@color/colorAccent"        custom:myTitle="111111111111111"/></LinearLayout>

运行起来的效果是这样的:
这里写图片描述

自定义view初体验,做到这里算是踏出一小步了。

0 0
原创粉丝点击