当前位置: 代码迷 >> Android >> Android-26-追随手指移动的小球
  详细解决方案

Android-26-追随手指移动的小球

热度:287   发布时间:2016-04-28 01:20:15.0
Android---26---跟随手指移动的小球

通过回调实现跟随手指移动的小球:

那么什么是回调,这里的回调是指Android中两种事件处理的方式之一。一种是通过监听器来实现的监听机制,一种是通过自身的方法实现的回调机制。


基于监听的处理机制,主要涉及三类对象:


EventSource(事件源):通常是各个组件;

Event(事件):对组件的操作;

EventListener(事件监听器):做出响应。

所谓事件监听器其实就是实现了特定接口的Java类的实例。

在程序中实现事件监听器,有四种形式:

1.内部类形式

2.外部类形式

3.Activity本身作为事件监听器

4.匿名内部类


一般来说,后两种较常用。



基于回调的监听机制:

事件源与事件监听器是统一的,或者说事件监听器消失了。

基于回调的事件处理可通过自定义View来实现。



两者有什么不同?



事件监听机制是一种委托式的事件处理,事件源与事件监听器不是统一的,或者说是分开的,不是一起的。

而基于回调的事件事件处理机制,事件源与事件监听器是一起的,不用通过监听器,自己就能实现。



基于回调的事件传播:

几乎所有的基于回调的事件处理方法都有一个boolean类型的返回值,该值用于标识该处理方法是否能完全处理该事件。


返回true,表明该处理方法已完全处理该事件,该事件不会传播出去

返回false,表明该处理方法没有完全处理该事件,该事件会传播出去。


对于基于回调的事件传播而言,某组件上所发生的事情不仅激发该组件上的回调方法,也会触发该组件所在Activity的回调方法----只要事件能传播到该Activity。



实例:


跟随手指移动的小球:自定义VIew


MainActivity.java:


package com.example.ontoucheventdemo;import android.app.Activity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;public class MainActivity extends Activity {	@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.activity_main);	}}




DrawViewDemo.java:


package com.example.ontoucheventdemo;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;public class DrawViewDemo extends View{	public float currentX = 40;	public float currentY = 50;	//定义。创建画笔	Paint p = new Paint();		public DrawViewDemo(Context context,AttributeSet set) {		// TODO Auto-generated constructor stub		super(context,set);	}		@Override	protected void onDraw(Canvas canvas) {		// TODO Auto-generated method stub		super.onDraw(canvas);		//设置画笔的颜色		p.setColor(Color.RED);		//绘制一个小球		//参数分别是:圆心坐标,半径 ,所使用的画笔		canvas.drawCircle(currentX, currentY, 15, p);			}		@Override	public boolean onTouchEvent(MotionEvent event) {		// TODO Auto-generated method stub		//修改当前的坐标		this.currentX = event.getX();		this.currentY = event.getY();		//重绘小球		this.invalidate();				return true;	}}


activity_main.xml:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.example.ontoucheventdemo.MainActivity" >    <com.example.ontoucheventdemo.DrawViewDemo         android:layout_width="fill_parent"        android:layout_height="fill_parent"        /></LinearLayout>







  相关解决方案