手势识别官方教程(8)拦截触摸事件,得到触摸的属性如速度,距离等,控制view展开
onInterceptTouchEvent可在onTouchEvent()前拦截触摸事件,
ViewConfiguration得到触摸的属性如速度,距离等,
TouchDelegate控制view展开
Managing Touch Events in a ViewGroup
Handling touch events in a ViewGroup
takes special care, because it's common for a ViewGroup
to have children that are targets for different touch events than the ViewGroup
itself. To make sure that each view correctly receives the touch events intended for it, override the onInterceptTouchEvent()
method.
Intercept Touch Events in a ViewGroup
The onInterceptTouchEvent()
method is called whenever a touch event is detected on the surface of a ViewGroup
, including on the surface of its children. If onInterceptTouchEvent()
returns true
, the MotionEvent
is intercepted, meaning it will be not be passed on to the child, but rather to the onTouchEvent()
method of the parent.
The onInterceptTouchEvent()
method gives a parent the chance to see any touch event before its children do. If you return true
from onInterceptTouchEvent()
, the child view that was previously handling touch events receives an ACTION_CANCEL
, and the events from that point forward are sent to the parent's onTouchEvent()
method for the usual handling. onInterceptTouchEvent()
can also return false
and simply spy on events as they travel down the view hierarchy to their usual targets, which will handle the events with their own onTouchEvent()
.
如果在ViewGroup的 onInterceptTouchEvent() 返回ture ,那么表示ViewGroup拦截这个事件,它和它的子view的onTouchEvent()不会被调用。
In the following snippet, the class MyViewGroup
extends ViewGroup
. MyViewGroup
contains multiple child views. If you drag your finger across a child view horizontally, the child view should no longer get touch events, and MyViewGroup
should handle touch events by scrolling its contents. However, if you press buttons in the child view, or scroll the child view vertically, the parent shouldn't intercept those touch events, because the child is the intended target. In those cases, onInterceptTouchEvent()
should return false
, and MyViewGroup
's onTouchEvent()
won't be called.
public class MyViewGroup extends ViewGroup { private int mTouchSlop; ... ViewConfiguration vc = ViewConfiguration.get(view.getContext());
mTouchSlop = vc.getScaledTouchSlop(); ... @Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
/*
* This method JUST determines whether we want to intercept the motion.
* If we return true, onTouchEvent will be called and we do the actual
* scrolling there.
*/ final int action = MotionEventCompat.getActionMasked(ev); // Always handle the case of the touch gesture being complete.
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
// Release the scroll.
mIsScrolling = false;
return false; // Do not intercept touch event, let the child handle it
} switch (action) {
case MotionEvent.ACTION_MOVE: {
if (mIsScrolling) {
// We're currently scrolling, so yes, intercept the
// touch event!
return true;
} // If the user has dragged her finger horizontally more than
// the touch slop, start the scroll // left as an exercise for the reader
final int xDiff = calculateDistanceX(ev); // Touch slop should be calculated using ViewConfiguration
// constants.
if (xDiff > mTouchSlop) {
// Start scrolling!
mIsScrolling = true;
return true;
}
break;
}
...
} // In general, we don't want to intercept touch events. They should be
// handled by the child view.
return false;
} @Override
public boolean onTouchEvent(MotionEvent ev) {
// Here we actually handle the touch event (e.g. if the action is ACTION_MOVE,
// scroll this container).
// This method will only be called if the touch event was intercepted in
// onInterceptTouchEvent
...
}
}
Note that ViewGroup
also provides a requestDisallowInterceptTouchEvent()
method. The ViewGroup
calls this method when a child does not want the parent and its ancestors to intercept touch events with onInterceptTouchEvent()
.
Use ViewConfiguration Constants
The above snippet uses the current ViewConfiguration
to initialize a variable called mTouchSlop
. You can use the ViewConfiguration
class to access common distances, speeds, and times used by the Android system.
"Touch slop" refers to the distance in pixels a user's touch can wander before the gesture is interpreted as scrolling. Touch slop is typically used to prevent accidental scrolling when the user is performing some other touch operation, such as touching on-screen elements.
Two other commonly used ViewConfiguration
methods are getScaledMinimumFlingVelocity()
and getScaledMaximumFlingVelocity()
. These methods return the minimum and maximum velocity (respectively) to initiate a fling, as measured in pixels per second. For example:
可以用ViewConfiguration的成员函数得到常用的数据,如:
vc.getScaledTouchSlop();
vc.getScaledMinimumFlingVelocity();
vc.getScaledMaximumFlingVelocity();等等
ViewConfiguration vc = ViewConfiguration.get(view.getContext());
private int mSlop = vc.getScaledTouchSlop();
private int mMinFlingVelocity = vc.getScaledMinimumFlingVelocity();
private int mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity(); ... case MotionEvent.ACTION_MOVE: {
...
float deltaX = motionEvent.getRawX() - mDownX;
if (Math.abs(deltaX) > mSlop) {
// A swipe occurred, do something
} ... case MotionEvent.ACTION_UP: {
...
} if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity
&& velocityY < velocityX) {
// The criteria have been satisfied, do something
}
}
Extend a Child View's Touchable Area
Android provides the TouchDelegate
class to make it possible for a parent to extend the touchable area of a child view beyond the child's bounds. This is useful when the child has to be small, but should have a larger touch region. You can also use this approach to shrink the child's touch region if need be.
In the following example, an ImageButton
is the "delegate view" (that is, the child whose touch area the parent will extend). Here is the layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parent_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" > <ImageButton android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"
android:src="@drawable/icon" />
</RelativeLayout>
The snippet below does the following:
- Gets the parent view and posts a
Runnable
on the UI thread. This ensures that the parent lays out its children before calling thegetHitRect()
method. ThegetHitRect()
method gets the child's hit rectangle (touchable area) in the parent's coordinates. - Finds the
ImageButton
child view and callsgetHitRect()
to get the bounds of the child's touchable area. - Extends the bounds of the
ImageButton
's hit rectangle. - Instantiates a
TouchDelegate
, passing in the expanded hit rectangle and theImageButton
child view as parameters. - Sets the
TouchDelegate
on the parent view, such that touches within the touch delegate bounds are routed to the child.
In its capacity as touch delegate for the ImageButton
child view, the parent view will receive all touch events. If the touch event occurred within the child's hit rectangle, the parent will pass the touch event to the child for handling.
public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the parent view
View parentView = findViewById(R.id.parent_layout); parentView.post(new Runnable() {
// Post in the parent's message queue to make sure the parent
// lays out its children before you call getHitRect()
@Override
public void run() {
// The bounds for the delegate view (an ImageButton
// in this example)
Rect delegateArea = new Rect();
ImageButton myButton = (ImageButton) findViewById(R.id.button);
myButton.setEnabled(true);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,
"Touch occurred within ImageButton touch region.",
Toast.LENGTH_SHORT).show();
}
}); // The hit rectangle for the ImageButton
myButton.getHitRect(delegateArea); // Extend the touch area of the ImageButton beyond its bounds
// on the right and bottom.
delegateArea.right += ;
delegateArea.bottom += ; // Instantiate a TouchDelegate.
// "delegateArea" is the bounds in local coordinates of
// the containing view to be mapped to the delegate view.
// "myButton" is the child view that should receive motion
// events.
TouchDelegate touchDelegate = new TouchDelegate(delegateArea,
myButton); // Sets the TouchDelegate on the parent view, such that touches
// within the touch delegate bounds are routed to the child.
if (View.class.isInstance(myButton.getParent())) {
((View) myButton.getParent()).setTouchDelegate(touchDelegate);
}
}
});
}
}
手势识别官方教程(8)拦截触摸事件,得到触摸的属性如速度,距离等,控制view展开的更多相关文章
- cocos2dX 事件之触摸事件和触摸事件集合
今天, 我们来学习cocos2dX里面的触摸事件与触摸事件合集, 如今的手机游戏交互基本上都是通过触摸交互的, 所以大家明确这节的重要性了吧, 本节篇幅比較大, 所以我就不扯闲话了 先来看看经常使用函 ...
- 手势识别官方教程(2)识别常见手势用GestureDetector+手势回调接口/手势抽象类
简介 GestureDetector识别手势. GestureDetector.OnGestureListener是识别手势后的回调接口.GestureDetector.SimpleOnGesture ...
- cocos2d-x游戏引擎核心之五——触摸事件和触摸分发器机制
一.触摸事件 为了处理屏幕触摸事件,Cocos2d-x 提供了非常方便.灵活的支持.在深入研究 Cocos2d-x 的触摸事件分发机制之前,我们利用 CCLayer 已经封装好的触摸接口来实现对简单的 ...
- cocos2dx中的触摸事件及触摸优先级
1.只有CCLayer及其派生类才有触摸功能. 2.开启触摸 setTouchEnable(true); 3.设置触摸模式,单点,多点(仅IOS支持) setTouchMode(kCCTouchesO ...
- 手势识别官方教程(7)识别缩放手势用ScaleGestureDetector.GestureDetector和ScaleGestureDetector.SimpleOnScaleGestureListener
Use Touch to Perform Scaling As discussed in Detecting Common Gestures, GestureDetector helps you de ...
- 手势识别官方教程(6)识别拖拽手势用GestureDetector.SimpleOnGestureListener和onTouchEvent
三种现实drag方式 1,在3.0以后可以直接用 View.OnDragListener (在onTouchEvent中调用某个view的startDrag()) 2,onTouchEvent() ...
- 手势识别官方教程(7)识别缩放手势用ScaleGestureDetector和SimpleOnScaleGestureListener
1.Use Touch to Perform Scaling As discussed in Detecting Common Gestures, GestureDetector helps you ...
- 下拉刷新控件(5)SwipeRefreshLayout官方教程(下)响应刷新事件
http://developer.android.com/training/swipe/respond-refresh-request.html This lesson shows you how t ...
- 手势识别官方教程(4)在挑划或拖动手势后view的滚动用ScrollView和 HorizontalScrollView,自定义用Scroller或OverScroller
简单滚动用ScrollView和 HorizontalScrollView就够.自定义view时可能要自定义滚动效果,可以使用 Scroller或 OverScroller Animating a S ...
随机推荐
- ajax学习笔记1
ajax是什么? ajax即“Asynchronous Javascript + XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术.能够快速的从服务器获得所需数据 ...
- xp 中的IIS安装成功之后,访问网页显示没有权限访问解决方法
在做xp的IIS发布网站时遇到一个问题就是当你访问网站的时候,显示没有权限访问网站,但是我已经开启了匿名访问网站了,怎么还没有权限访问呢?后来经过上网搜资料解决,当时很多网上都说没打开匿名访问,当时我 ...
- [记录 ]升级IOS 9 和 XCode 7 引起的问题
问题一: 升级xcode 7最低的系统配置要求 升级了ios9 后使用 xcode 6.1 已经不能用了,必须升级 xcode 7才行,原先的系统是OSX 10.10.1 版本.而xcode 7.0 ...
- CruiseControl.NET : svnrevisionlabeller
How to use svnrevisionlabeller as your labeller type in CC.NET: 1. Download ccnet.SvnRevisionLabelle ...
- Linux查找软件的安装路径
软件安装的路径可能不止一个,可以使用whereis命令查看软件安装的所有路径,以mysql为例: whereis mysql 该命令会返回软件的所有安装路径: mysql: /usr/bin/mysq ...
- 构造SEH来实现跳转-转载
下面的代码出自CSDN Delphi版的一高人(kiboisme 蓝色光芒) procedure ExceptProc{ExceptionRecord,SEH,Context,DispatcherCo ...
- jenkins 重新设置 管理员密码
由于服务器瘫痪,修好之后经常不上,就把jenkins的管理密码忘掉了. 查阅了网上所有方案之后发现没有一个 能正确修改密码的,特此列出下列网上的方法 第一.设成无需密码验证的(网上有教程,不过并不能修 ...
- 要成为开发中最牛逼的测试,测试中最牛逼的开发。从今天起学python,写博客。--python基础学习(一)
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32Type & ...
- python27读书笔记0.3
#-*- coding:utf-8 -*- ##D.has_key(k): A predicate that returns True if D has a key k.##D.items(): Re ...
- #Leet Code# Unique Path(todo)
描述: 使用了递归,有些计算是重复的,用了额外的空间,Version 1是m*n Bonus:一共走了m+n步,例如 m = 2, n = 3 [#, @, @, #, @],所以抽象成数学问题,解是 ...