重写onTouchEvent方法响应触摸屏事件

下面的程序重写了View组件的onTouchEvent(MotionEvent event)方法,这表示该组件自己就可以处理触摸屏事件,当用户手指在屏幕上移动时,该View上绘制的小球将会跟随用户手指。

drawview.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
<org.crazyit.event.DrawView
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />    

</LinearLayout>


 

DrawView.xml:

package com.example.helloandroid;

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 DrawView extends View{
	public float currentX=40;
	public float currentY=50;
	public DrawView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}
	public void onDraw(Canvas canvas)
	{
		super.onDraw(canvas);
		Paint p=new Paint();
		p.setColor(Color.RED);
		canvas.drawCircle(currentX, currentY, 15, p);
	}
	public boolean onTouchEvent(MotionEvent event){
		this.currentX=event.getX();
		this.currentY=event.getY();
		this.invalidate();
		return true;
	}

	

}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为了重写RecycleView的ontouchevent方法,您需要创建一个继承自RecyclerView的自定义类,并覆盖其中的onTouchEvent方法。这样,您就可以在RecycleView上捕获触摸事件,并执行您想要的动作。 以下是一个示例,演示了如何创建一个自定义RecycleView类并重写onTouchEvent方法来捕获触摸事件: ```java public class CustomRecyclerView extends RecyclerView { public CustomRecyclerView(Context context) { super(context); } public CustomRecyclerView(Context context, AttributeSet attrs) { super(context, attrs); } public CustomRecyclerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean onTouchEvent(MotionEvent e) { switch (e.getAction()) { case MotionEvent.ACTION_DOWN: // 处理按下事件 break; case MotionEvent.ACTION_MOVE: // 处理移动事件 break; case MotionEvent.ACTION_UP: // 处理抬起事件 break; } return super.onTouchEvent(e); } } ``` 在上述代码中,我们创建了一个继承自RecyclerView的CustomRecyclerView类,并覆盖了其onTouchEvent方法。在该方法中,我们使用switch语句来检测触摸事件的类型,并在不同情况下执行不同的动作。然后,我们返回父类实现的onTouchEvent方法,以确保RecycleView的基本触点操作能够正常工作。 在您完成自定义RecyclerView类的编写之后,您可以像使用常规RecyclerView一样使用它。只需在XML布局中使用CustomRecyclerView标记,或在代码中通过实例化来使用它。重写RecyclerView的onTouchEvent方法后,您可以在其中执行自定义操作,例如捕捉手势、模拟滚动等等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值