【UI】【View】随手指运动的小球

来源:互联网 发布:mysql怎么打开 编辑:程序博客网 时间:2024/05/17 17:16

本篇博客,记录一下学习自定义View的过程。

View实际上是一个空白的区域,自定义View 时实际上就是在这个空白区域进行自己的测量,布局和绘制。

View中有许多方法可以重写,根据需求重写需要的方法。


================================================================================================

以下是自定义View的代码,随手指运动的小球:

package com.example.trackball_test;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.util.AttributeSet;import android.util.Log;import android.view.MotionEvent;import android.view.View;public class TrackBall_test extends View {public final static String TRACKBALL_TAG = "TrackBall";    private Float currentX =(float) 50;private Float currentY =(float) 100;private Float radius = (float) 20;public TrackBall_test(Context context) {super(context);}public TrackBall_test(Context context, AttributeSet attrs) {super(context, attrs);}public TrackBall_test(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}@Overridepublic boolean onTouchEvent(MotionEvent event){currentX=event.getX();currentY=event.getY();Log.d(TRACKBALL_TAG, "x="+currentX+",y="+currentY);        //清除view,重绘        invalidate();return true;}@Overridepublic void onDraw(Canvas canvas){super.onDraw(canvas);Paint p = new Paint();p.setColor(Color.RED);//画一个圆canvas.drawCircle(currentX, currentY, radius, p);Log.d(TRACKBALL_TAG, "x="+currentX+",y="+currentY);}}


0 0
原创粉丝点击