您当前的位置: 首页 >  android

[Android]笔记3-跟随手指的小球

发布时间:2017-05-08 15:27:48 ,浏览量:1

为了实现一个跟随的小球,自定义UI组件,这个UI组件将会在指定位置绘制一个小球,这个位置可以动态改变。当用户通过手指在屏幕上拖动时,程序监听这个手指动作,把手指的位置传入自定义UI组件,并通知该组件重绘制即可。

DrawView UI组件

package com.dezai.customerviewactivity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; /**
 * Created by A292 on 2017/5/8.
 */ public class DrawView extends View { public float currentX=40; public float currentY=50;
    Paint p=new Paint(); public DrawView(Context context) { super(context);
    } public DrawView(Context context, AttributeSet set){ super(context,set);
    } @Override public void onDraw(Canvas canvas){ super.onDraw(canvas); //设置画笔颜色 p.setColor(Color.RED); //绘制一个小圆(作为一个小球) canvas.drawCircle(currentX,currentY,25,p);
    } @Override public boolean onTouchEvent(MotionEvent event){ //修改currentX currentY 两个属性 currentX =event.getX();
        currentY=event.getY(); //通知当前组件重绘制自己 invalidate(); //返回true表明该处理方法已处理该事件 return true;
    }
}

XML:

 <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.dezai.customerviewactivity.MainActivity"> <LinearLayout  android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:id="@+id/root"> <com.dezai.customerviewactivity.DrawView  android:layout_width="match_parent" android:layout_height="match_parent" /> LinearLayout> android.support.constraint.ConstraintLayout> 

MainActivity

package com.dezai.customerviewactivity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

这里写图片描述

关注
打赏
1688896170
查看更多评论

暂无认证

  • 1浏览

    0关注

    107766博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0506s