首页 > 学院 > 开发设计 > 正文

自定义拖动小球

2019-11-09 16:11:27
字体:
来源:转载
供稿:网友

今天我们来写一个自定义小球 实现拖动效果

首先我们来看下布局文件怎么写 下面这个呢就是mainActivity的布局文件

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.customviewi.customview.MainActivity">    <com.customviewi.customview.DrawView        android:id="@+id/qiu"        android:layout_width="match_parent"        android:layout_height="match_parent"         /></RelativeLayout>下面来看一下我们自己写的类中的代码

package com.customviewi.customview;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.util.AttributeSet;import android.util.FloatMath;import android.view.MotionEvent;import android.view.View;/** *  */public class DrawView extends View {    //成员变量    PRivate int width;    private int height;    private int x;    private int y;    private Boolean onBall;    public DrawView(Context context) {        this(context,null);    }    public DrawView(Context context, AttributeSet attrs) {        this(context, attrs,0);    }    public DrawView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    /**     * 测量方法     */    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        super.onMeasure(widthMeasureSpec, heightMeasureSpec);        //得到小球的宽高,默认占满全屏幕        width=this.getWidth();        height=this.getHeight();        //设置小球的位置        x=width/2;        y=height/2;    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        //创建画笔        Paint paint=new Paint();        //设置画笔的颜色        paint.setColor(Color.RED);        // 画出小球,前俩参数是代表圆在屏幕上的xy坐标,20是半径        canvas.drawCircle(x,y,20,paint);    }    /**     * 触摸事件     */    @Override    public boolean onTouchEvent(MotionEvent event) {        switch (event.getAction()){            case MotionEvent.ACTION_DOWN:                //得到当前的坐标点                float x2=event.getX();                float y2=event.getY();                //判断鼠标是不是在球 ,如果不用这个方法的话就会出现,点击屏幕的任何位置小球就会过去//                onBall=isonBall(x2,y2);                break;            case MotionEvent.ACTION_MOVE:                x= (int) event.getX();                y= (int) event.getY();                //这个方法可以从新调用onDraw                postInvalidate();                break;            case MotionEvent.ACTION_UP:                break;        }        return true;    }//    public boolean isonBall(float x2,float y2) {////        float sqrt = FloatMath.sqrt((x2-x)*(x2-x)+(y2-y)*(y2-y));//        float sqrt=FloatMath.//        return onBall;//    }}这样呢 我们的自定义的小球就实现拖动效果了


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表