Android_ListView_onTouchEvent源码分析

2024-02-06 22:08

本文主要是介绍Android_ListView_onTouchEvent源码分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Android ListView  onTouchEvent源码简单分析,在看代码之前先来看下代码结构图


1.onTouchEvent源码

    @Overridepublic boolean onTouchEvent(MotionEvent ev) {if (!isEnabled()) {// A disabled view that is clickable still consumes the touch// events, it just doesn't respond to them.return isClickable() || isLongClickable();}// AbsListView 绘制与控制手指快速滚动的辅助类if (mFastScroller != null) {boolean intercepted = mFastScroller.onTouchEvent(ev);if (intercepted) {return true;}}final int action = ev.getAction();View v;int deltaY;// 获取触摸滚动时的速率if (mVelocityTracker == null) {mVelocityTracker = VelocityTracker.obtain();}mVelocityTracker.addMovement(ev);// ListView触屏事件主要从ACTION操作划分switch (action & MotionEvent.ACTION_MASK) {case MotionEvent.ACTION_DOWN: {......break;}case MotionEvent.ACTION_MOVE: {......break;}case MotionEvent.ACTION_UP: {switch (mTouchMode) {case TOUCH_MODE_DOWN:case TOUCH_MODE_TAP:case TOUCH_MODE_DONE_WAITING:......mTouchMode = TOUCH_MODE_REST;break;case TOUCH_MODE_SCROLL:......break;}setPressed(false);// Need to redraw since we probably aren't drawing the selector anymoreinvalidate();final Handler handler = getHandler();if (handler != null) {handler.removeCallbacks(mPendingCheckForLongPress);}if (mVelocityTracker != null) {mVelocityTracker.recycle();mVelocityTracker = null;}mActivePointerId = INVALID_POINTER;if (PROFILE_SCROLLING) {if (mScrollProfilingStarted) {Debug.stopMethodTracing();mScrollProfilingStarted = false;}}break;}case MotionEvent.ACTION_CANCEL: {mTouchMode = TOUCH_MODE_REST;......break;}case MotionEvent.ACTION_POINTER_UP: {......break;}}return true;}

2.ACTION_DOWN,主要是CheckForTap

        case MotionEvent.ACTION_DOWN: {mActivePointerId = ev.getPointerId(0);final int x = (int) ev.getX();final int y = (int) ev.getY();// 手指按下时x,y坐标,获取当前选中的itemint motionPosition = pointToPosition(x, y);// 如果ListView 数据未发生变化if (!mDataChanged) {if ((mTouchMode != TOUCH_MODE_FLING) && (motionPosition >= 0)&& (getAdapter().isEnabled(motionPosition))) {// User clicked on an actual view (and was not stopping a fling). It might be a// click or a scroll. Assume it is a click until proven otherwisemTouchMode = TOUCH_MODE_DOWN;// TAP机制,主要是用于去除手指点击抖动// 使Item处于按下状态if (mPendingCheckForTap == null) {mPendingCheckForTap = new CheckForTap();}// 添加到消息队列并延时ViewConfiguration.getTapTimeout()执行此runnablepostDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());} else {if (ev.getEdgeFlags() != 0 && motionPosition < 0) {// If we couldn't find a view to click on, but the down event was touching// the edge, we will bail out and try again. This allows the edge correcting// code in ViewRoot to try to find a nearby view to selectreturn false;}// 之前处于Fling模式if (mTouchMode == TOUCH_MODE_FLING) {// Stopped a fling. It is a scroll.createScrollingCache();// 更改为scrollmTouchMode = TOUCH_MODE_SCROLL;mMotionCorrection = 0;motionPosition = findMotionRow(y);reportScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);}}}// 对于ACTION_MOVE,ACTION_UP会使用的触屏位置信息进行记录if (motionPosition >= 0) {// Remember where the motion event startedv = getChildAt(motionPosition - mFirstPosition);mMotionViewOriginalTop = v.getTop();}mMotionX = x;mMotionY = y;mMotionPosition = motionPosition;mLastY = Integer.MIN_VALUE;break;}

3.ACTION_MOVE,主要是startScrollIfNeeded和trackMotionScroll

        case MotionEvent.ACTION_MOVE: {final int pointerIndex = ev.findPointerIndex(mActivePointerId);final int y = (int) ev.getY(pointerIndex);// 获取y轴当前与前一次的偏移值deltaY = y - mMotionY;switch (mTouchMode) {case TOUCH_MODE_DOWN:case TOUCH_MODE_TAP:case TOUCH_MODE_DONE_WAITING:// 必须移动一段距离后才会执行滚动startScrollIfNeeded(deltaY);break;case TOUCH_MODE_SCROLL:if (PROFILE_SCROLLING) {if (!mScrollProfilingStarted) {Debug.startMethodTracing("AbsListViewScroll");mScrollProfilingStarted = true;}}// 手指移动if (y != mLastY) {deltaY -= mMotionCorrection;int incrementalDeltaY = mLastY != Integer.MIN_VALUE ? y - mLastY : deltaY;// No need to do all this work if we're not going to move anywayboolean atEdge = false;if (incrementalDeltaY != 0) {// 滚动的重要方法,滚动的具体处理就是这里atEdge = trackMotionScroll(deltaY, incrementalDeltaY);}// ListView滚动到边界后不不能再进行移动if (atEdge && getChildCount() > 0) {// Treat this like we're starting a new scroll from the current// position. This will let the user start scrolling back into// content immediately rather than needing to scroll back to the// point where they hit the limit first.int motionPosition = findMotionRow(y);if (motionPosition >= 0) {final View motionView = getChildAt(motionPosition - mFirstPosition);mMotionViewOriginalTop = motionView.getTop();}mMotionY = y;mMotionPosition = motionPosition;invalidate();}// 记录当前Y值,用于下次计算偏移量mLastY = y;}break;}break;}

4.ACTION_UP,主要是PerformClick, mPendingCheckForLongPress, mFlingRunnable

        case MotionEvent.ACTION_UP: {switch (mTouchMode) {case TOUCH_MODE_DOWN:case TOUCH_MODE_TAP:case TOUCH_MODE_DONE_WAITING:final int motionPosition = mMotionPosition;final View child = getChildAt(motionPosition - mFirstPosition);if (child != null && !child.hasFocusable()) {// 清理Item按下状态if (mTouchMode != TOUCH_MODE_DOWN) {child.setPressed(false);}// 执行Item Clickif (mPerformClick == null) {mPerformClick = new PerformClick();}final AbsListView.PerformClick performClick = mPerformClick;performClick.mChild = child;performClick.mClickMotionPosition = motionPosition;performClick.rememberWindowAttachCount();mResurrectToPosition = motionPosition;if (mTouchMode == TOUCH_MODE_DOWN || mTouchMode == TOUCH_MODE_TAP) {final Handler handler = getHandler();if (handler != null) {// 清理tap或者long press长按handler.removeCallbacks(mTouchMode == TOUCH_MODE_DOWN ?mPendingCheckForTap : mPendingCheckForLongPress);}mLayoutMode = LAYOUT_NORMAL;if (!mDataChanged && mAdapter.isEnabled(motionPosition)) {mTouchMode = TOUCH_MODE_TAP;setSelectedPositionInt(mMotionPosition);layoutChildren();child.setPressed(true);positionSelector(child);setPressed(true);if (mSelector != null) {Drawable d = mSelector.getCurrent();if (d != null && d instanceof TransitionDrawable) {((TransitionDrawable) d).resetTransition();}}postDelayed(new Runnable() {public void run() {child.setPressed(false);setPressed(false);if (!mDataChanged) {post(performClick);}mTouchMode = TOUCH_MODE_REST;}}, ViewConfiguration.getPressedStateDuration());} else {mTouchMode = TOUCH_MODE_REST;}return true;} else if (!mDataChanged && mAdapter.isEnabled(motionPosition)) {post(performClick);}}mTouchMode = TOUCH_MODE_REST;break;case TOUCH_MODE_SCROLL:final int childCount = getChildCount();if (childCount > 0) {if (mFirstPosition == 0 && getChildAt(0).getTop() >= mListPadding.top &&mFirstPosition + childCount < mItemCount &&getChildAt(childCount - 1).getBottom() <=getHeight() - mListPadding.bottom) {mTouchMode = TOUCH_MODE_REST;reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);} else {// 是否执行ListView Scroll Flingfinal VelocityTracker velocityTracker = mVelocityTracker;velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);// 获取当前触屏滚动速率final int initialVelocity = (int) velocityTracker.getYVelocity(mActivePointerId);if (Math.abs(initialVelocity) > mMinimumVelocity) {if (mFlingRunnable == null) {mFlingRunnable = new FlingRunnable();}reportScrollStateChange(OnScrollListener.SCROLL_STATE_FLING);// 执行ListView 快速滚动(Scroll Fling)mFlingRunnable.start(-initialVelocity);} else {mTouchMode = TOUCH_MODE_REST;reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);}}} else {mTouchMode = TOUCH_MODE_REST;reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);}break;}setPressed(false);// Need to redraw since we probably aren't drawing the selector anymoreinvalidate();final Handler handler = getHandler();if (handler != null) {handler.removeCallbacks(mPendingCheckForLongPress);}if (mVelocityTracker != null) {mVelocityTracker.recycle();mVelocityTracker = null;}mActivePointerId = INVALID_POINTER;if (PROFILE_SCROLLING) {if (mScrollProfilingStarted) {Debug.stopMethodTracing();mScrollProfilingStarted = false;}}break;}

这篇关于Android_ListView_onTouchEvent源码分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/685690

相关文章

Go中sync.Once源码的深度讲解

《Go中sync.Once源码的深度讲解》sync.Once是Go语言标准库中的一个同步原语,用于确保某个操作只执行一次,本文将从源码出发为大家详细介绍一下sync.Once的具体使用,x希望对大家有... 目录概念简单示例源码解读总结概念sync.Once是Go语言标准库中的一个同步原语,用于确保某个操

Redis主从/哨兵机制原理分析

《Redis主从/哨兵机制原理分析》本文介绍了Redis的主从复制和哨兵机制,主从复制实现了数据的热备份和负载均衡,而哨兵机制可以监控Redis集群,实现自动故障转移,哨兵机制通过监控、下线、选举和故... 目录一、主从复制1.1 什么是主从复制1.2 主从复制的作用1.3 主从复制原理1.3.1 全量复制

Redis主从复制的原理分析

《Redis主从复制的原理分析》Redis主从复制通过将数据镜像到多个从节点,实现高可用性和扩展性,主从复制包括初次全量同步和增量同步两个阶段,为优化复制性能,可以采用AOF持久化、调整复制超时时间、... 目录Redis主从复制的原理主从复制概述配置主从复制数据同步过程复制一致性与延迟故障转移机制监控与维

Redis连接失败:客户端IP不在白名单中的问题分析与解决方案

《Redis连接失败:客户端IP不在白名单中的问题分析与解决方案》在现代分布式系统中,Redis作为一种高性能的内存数据库,被广泛应用于缓存、消息队列、会话存储等场景,然而,在实际使用过程中,我们可能... 目录一、问题背景二、错误分析1. 错误信息解读2. 根本原因三、解决方案1. 将客户端IP添加到Re

Java汇编源码如何查看环境搭建

《Java汇编源码如何查看环境搭建》:本文主要介绍如何在IntelliJIDEA开发环境中搭建字节码和汇编环境,以便更好地进行代码调优和JVM学习,首先,介绍了如何配置IntelliJIDEA以方... 目录一、简介二、在IDEA开发环境中搭建汇编环境2.1 在IDEA中搭建字节码查看环境2.1.1 搭建步

Redis主从复制实现原理分析

《Redis主从复制实现原理分析》Redis主从复制通过Sync和CommandPropagate阶段实现数据同步,2.8版本后引入Psync指令,根据复制偏移量进行全量或部分同步,优化了数据传输效率... 目录Redis主DodMIK从复制实现原理实现原理Psync: 2.8版本后总结Redis主从复制实

锐捷和腾达哪个好? 两个品牌路由器对比分析

《锐捷和腾达哪个好?两个品牌路由器对比分析》在选择路由器时,Tenda和锐捷都是备受关注的品牌,各自有独特的产品特点和市场定位,选择哪个品牌的路由器更合适,实际上取决于你的具体需求和使用场景,我们从... 在选购路由器时,锐捷和腾达都是市场上备受关注的品牌,但它们的定位和特点却有所不同。锐捷更偏向企业级和专

Android数据库Room的实际使用过程总结

《Android数据库Room的实际使用过程总结》这篇文章主要给大家介绍了关于Android数据库Room的实际使用过程,详细介绍了如何创建实体类、数据访问对象(DAO)和数据库抽象类,需要的朋友可以... 目录前言一、Room的基本使用1.项目配置2.创建实体类(Entity)3.创建数据访问对象(DAO

Spring中Bean有关NullPointerException异常的原因分析

《Spring中Bean有关NullPointerException异常的原因分析》在Spring中使用@Autowired注解注入的bean不能在静态上下文中访问,否则会导致NullPointerE... 目录Spring中Bean有关NullPointerException异常的原因问题描述解决方案总结

python中的与时间相关的模块应用场景分析

《python中的与时间相关的模块应用场景分析》本文介绍了Python中与时间相关的几个重要模块:`time`、`datetime`、`calendar`、`timeit`、`pytz`和`dateu... 目录1. time 模块2. datetime 模块3. calendar 模块4. timeit