Android自定义View讲解加示例

来源:互联网 发布:抑毛液有用吗 知乎 编辑:程序博客网 时间:2024/06/05 19:36


Android自定义View是工程开发中必不可少的一项技能,项目中通过自定义View的方式造好各种内部需要的View,将会带来极大的使用方便。


一、自定义View的几种使用方式

(1)自绘控件:使用canvas画出控件的样子

(2)组合一些Android的控件:通过继承容器,将一些现有的组件组合起来成为一个固定的View

(3)继承并扩展Android的控件:对原有的Android View进行扩展,在原有功能上添加新的功能。

相对来说,组合和继承比较容易,自绘控件要稍微复杂一点。本次将主要讲解自绘控件的方式,并通过一个具体的例子,展示怎么画出一个控件、怎么自定义属性来控制控件的样式、并为控件添加一些行为特征。


二、使用自定义View,一般需重写以下4个方法,但不是必须都重写,根据需要选择性重写即可。

onMeasure():测量控件本身的大小onLayout():测量控件在父控件中的位置onDraw():构建了自定义View的外观形象onTouchEvent():重载视图的行为</span>


三、示范制作一个自定View

本例子将制作一个自定义View,样式为一张小火箭图片,xml中可以通过自定义属性控制其样式,点击小火箭将开始一个翻转动画。好了,开始上代码。

1. 设计自定义属性

首先在res/values/  下建立一个attrs.xml , 在里面定义我们的属性和声明我们的整个样式。

 <?xml version="1.0" encoding="utf-8"?>          <resources>             <declare-styleable name="MyTouchBall">                 <attr name="imgSampleSize" format="integer" />                 <attr name="duration" format="integer" />             </declare-styleable>         </resources></span></span>


2.新建一个类MyTouchBall,继承View,布局文件中像用Android自带控件一样使用自定义View,注意引入命名控件(代码第4行),通过命名空间方便使用自定义属性

<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:mytouchball="http://schemas.android.com/apk/res/com.example.administrator.myapplication"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.example.administrator.myapplication.MainActivity"    >    <com.example.administrator.myapplication.MyTouchBall        android:layout_width="500dp"        android:layout_height="wrap_content"        mytouchball:duration="1000"        mytouchball:imgSampleSize="1"        >    </com.example.administrator.myapplication.MyTouchBall></RelativeLayout></span></span>

3. 自定义View,这里会有三个默认的构造方法,android开发者网站上有相关的说明文档: 

public View (Context context)是在java代码创建视图的时候被调用,如从xml填充的视图,就不会调用这个 。public View (Context context, AttributeSet attrs)这个是在xml创建但是没有指定style的时候被调用 public View (Context context, AttributeSet attrs, int defStyle)给View提供一个基本的style</span>

我们在两个参数的构造方法中,添加逻辑,接受xml布局中的自定义属性。

public class MyTouchBall extends View {    private int mImgSampleSize = 10;  //火箭缩放比例    private int mDuration = 500;  //火箭动画的时间    private Bitmap mBitmap;    private int mImgHeight; //缩放后,图片的实际高度    private int mImgWidth;  //缩放后,图片的实际宽度    private Paint mPaint; //画笔    public MyTouchBall(Context context) {        super(context);    }    //在这里获取自定义属性,并赋值给成员变量    public MyTouchBall(Context context, AttributeSet attrs) {        super(context, attrs);        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyTouchBall);        int count = typedArray.getIndexCount();        for (int i = 0; i < count; i++) {            int attr = typedArray.getIndex(i);            switch (attr) {                case R.styleable.MyTouchBall_duration:                    mDuration = typedArray.getInteger(attr, 500);                    break;                case R.styleable.MyTouchBall_imgSampleSize:                    mImgSampleSize = typedArray.getInteger(attr, 30);                    break;                default:                    break;            }        }        setBackgroundColor(getResources().getColor(R.color.sandybrown));//设置背景颜色为浅黄色,方便识别onMeasure计算的对不对        typedArray.recycle();        //根据属性计算火箭图片的宽高        mBitmap = decodeSampledBitmap(getResources(), R.mipmap.roket, mImgSampleSize);        mImgWidth = mBitmap.getWidth();        mImgHeight = mBitmap.getHeight();    }    public MyTouchBall(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }  }</span></span>

decodeSampledBitmap方法是根据缩放比例,压缩或放大图片,下面是它的代码。

<span style="font-family:SimSun;"><span style="font-family:SimSun;font-size:14px;">  //加载图片,按比例缩放    private static Bitmap decodeSampledBitmap(Resources res, int resId, int sampleSize) {        final BitmapFactory.Options options = new BitmapFactory.Options();        options.inJustDecodeBounds = false;        options.inSampleSize = sampleSize;        // 使用获取到的inSampleSize值解析图片        return BitmapFactory.decodeResource(res, resId, options);    }</span></span>

4. 重写onMeasure方法,根据xml属性来决定控件的宽高。

  如下问代码所示,一般自定义控件都会重写View的onMeasure方法,因为该方法指定该控件在屏幕上的大小。
  

  onMeasure(int widthMeasureSpec, int heightMeasureSpec)传入的两个参数是由上一层控件传入的大小,有多种情况,重写该方法时需要对计算控件的实际大小,然后调用setMeasuredDimension(int, int)设置实际大小。

  onMeasure传入的widthMeasureSpec和heightMeasureSpec不是一般的尺寸数值,而是将模式和尺寸组合在一起的数值。

  通过int mode = MeasureSpec.getMode(widthMeasureSpec)得到模式,用int size =?MeasureSpec.getSize(widthMeasureSpec)得到尺寸。

  其中,mode共有三种情况,取值分别为MeasureSpec.UNSPECIFIED, MeasureSpec.EXACTLY, MeasureSpec.AT_MOST。

  MeasureSpec.EXACTLY是精确尺寸,当我们将自定义View的layout_width或layout_height指定为具体数值时如andorid:layout_width="50dip",或者match_parent就会是这个模式。(match_parent也相当于指定了具体尺寸)

  MeasureSpec.AT_MOST是最大尺寸,当控件的layout_width或layout_height指定为WRAP_CONTENT时,控件大小一般随着控件的子空间或内容进行变化,此时控件尺寸只要不超过父控件允许的最大尺寸即可。因此,此时的mode是AT_MOST,size给出了父控件允许的最大尺寸。

  MeasureSpec.UNSPECIFIED是未指定尺寸,这种情况不多.

 

  简单总结,映射关系是:
   wrap_parent -> MeasureSpec.AT_MOST
   具体数值或者match_parent -> MeasureSpec.EXACTLY

<span style="font-family:SimSun;"><span style="font-family:SimSun;font-size:14px;">    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        int widthSize = MeasureSpec.getSize(widthMeasureSpec);        int heightSize = MeasureSpec.getSize(heightMeasureSpec);        int widthMode = MeasureSpec.getMode(widthMeasureSpec);        int heightMode = MeasureSpec.getMode(heightMeasureSpec);        int width, height;        if (widthMode == MeasureSpec.EXACTLY) { //使用者在布局文件里指定了具体的宽度            width = widthSize;        } else {  //没有指定,或者设置成了wrap_content            //这时候要计算具体的数值,宽度取图片的宽度            width = mImgWidth;        }        if (heightMode == MeasureSpec.EXACTLY) { //使用者在布局文件里指定了具体的高度            height = heightSize;        } else {  //没有指定,或者设置成了wrap_content            //宽度取图片的高度            height = mImgHeight;        }        setMeasuredDimension(width, height);    }</span></span>

5. 重写onDraw方法,画出具体的界面,这里就是将一张图片画到界面上(当然,你可以根据需要画各种形状)。

<span style="font-family:SimSun;"><span style="font-family:SimSun;font-size:14px;">    @Override    protected void onDraw(Canvas canvas) {        mPaint = new Paint();        canvas.drawBitmap(mBitmap, 0, 0, mPaint);//在画布上画出图片    }</span></span>

6. 重写onTouchEvent方法,为控件添加一些独特的行为,默认返回值用false,以便事件能回传到上层,不影响原有功能。具体原因请看我的另一篇博客Android事件传递机制详解(嵌套自定义View示例)

<span style="font-family:SimSun;"><span style="font-family:SimSun;font-size:14px;">    @Override    public boolean onTouchEvent(MotionEvent event) {        if (event.getAction() == MotionEvent.ACTION_DOWN) {            startAnimation();        }        return false;    }</span></span>

7. 一个简单的旋转动画效果

<span style="font-family:SimSun;"><span style="font-family:SimSun;font-size:14px;">  //开始动画    public void startAnimation() {        ObjectAnimator.ofFloat(this, "rotationX", 0.0f, 360.0f).setDuration(mDuration).start();    }</span></span>

三、结果

好了,大功告成,通过结果来看看效果吧。从之前的布局文件可以看到,因为宽度设置了500dp,整个控件的大小是500dp(通过背景色可以看出来);而高度设置的是wrap_content,所以控件的高度就是图片的高度。这表明onMeasure的效果已经达到了。



如果觉得我的文章对你有用,请留言鼓励一下吧!

1 0
原创粉丝点击