Android学习笔记(四)——简单的控件和基本响应:(触屏)运动事件的响应(2)View的继承和onDraw的重载

依旧是对于触屏运动事件的学习,但并未使用布局文件进行布局,而是通过继承View类并重载其中的ondraw函数和事件处理函数

package com.shine.night;

import android.app.Activity;
import android.content.Context;
import android.graphics.*;
import android.os.Bundle;
import android.util.Log;

import android.view.MotionEvent;
import android.view.View;
//没有用布局文件
public class MainActivity extends Activity 
{
    protected void onCreate ( Bundle b )
    {
        super.onCreate ( b );
        setContentView (  new TestMotionView ( this ) );
    }
    
    public class TestMotionView extends View 
    {
        private Paint mPaint = new Paint ( );
        private int mAction;
        private float x;
        private float y;
        //context类,用于识别调用者的实例
        public TestMotionView ( Context c )
        {
            super ( c );
            mAction = MotionEvent.ACTION_UP;
            x = 0;
            y = 0;
        }
        //继承自view类,能够绘出图像
        protected void onDraw ( Canvas canvas )
        {
            Paint paint  = mPaint;
            canvas.drawColor ( Color.WHITE );
            if ( MotionEvent.ACTION_MOVE == mAction )//移动动作
                paint.setColor ( Color.RED );
            else if ( MotionEvent.ACTION_UP == mAction )//抬起动作
                paint.setColor ( Color.GREEN );
            else if ( MotionEvent.ACTION_DOWN == mAction )//按下动作
                paint.setColor ( Color.BLUE );
            //绘制圆 , 并且利用画笔对它进行着色
            canvas.drawCircle ( x , y , 10 , paint );
            setTitle ( "A = " + mAction + "[" + x + "," + y + "]" ); 
        }
        //对该类的事件处理函数进行定义
        public boolean onTouchEvent ( MotionEvent event )
        {
            mAction = event.getAction ();
            x = event.getX ();
            y = event.getY ();
            invalidate ();
            return true;
        }
    }
}


你可能感兴趣的:(android,继承,Android开发,布局,控件)