自定义View实现跟随手指的小球
Posted zqxLonely
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义View实现跟随手指的小球相关的知识,希望对你有一定的参考价值。
package com.pingyijinren.test; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; /** * Created by Administrator on 2016/5/21 0021. */ public class DrawView extends View { private float x=100; private float y=100; public DrawView(Context context){ super(context); } //自定义View时,必须实现View的三个构造函数 public DrawView(Context context, AttributeSet attrs){ super(context,attrs); } public DrawView(Context context, AttributeSet attrs, int defStyle){ super(context,attrs,defStyle); } @Override public void onDraw(Canvas canvas){ //onDraw不是必需的,按需重写即可 super.onDraw(canvas); Paint paint=new Paint(); paint.setColor(Color.RED); canvas.drawCircle(x,y,100,paint); } public void setX(float x){ this.x=x; } public void setY(float y){ this.y=y; } }
<?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:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.pingyijinren.test.MainActivity"> <com.pingyijinren.test.DrawView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/drawView"/> </RelativeLayout>
package com.pingyijinren.test; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; public class MainActivity extends AppCompatActivity { private DrawView drawView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try{ setContentView(R.layout.activity_main); } catch(Exception e){ e.printStackTrace(); Log.d("MainActivity",e.getMessage()); } drawView=(DrawView)findViewById(R.id.drawView); drawView.setOnTouchListener(new View.OnTouchListener() { //drawView响应屏幕触摸事件 @Override public boolean onTouch(View v, MotionEvent event) { drawView.setX(event.getX()); drawView.setY(event.getY()); drawView.invalidate(); return true; } }); } }
以上是关于自定义View实现跟随手指的小球的主要内容,如果未能解决你的问题,请参考以下文章