3.View的事件体系 (上):必须了解的基础知识

1.为什么要了解View

android.view.View
界面层控件的一种抽象,是android系统中所有控件的基类。

2.MotionEvent与TouchSlop

  • MotionEvent :手指接触屏幕传递的事件对象

    通常关心较多的有3个事件类型:

    public static final int ACTION_UP               = 1;
    public static final int ACTION_MOVE             = 2;
    public static final int ACTION_CANCEL           = 3;

获取坐标:
getX/getY 相对当前View左上角的x和y坐标
getRawX/getRawY 相对手机屏幕左上角的x和y坐标

     /**
     * {@link #getX(int)} for the first pointer index (may be an
     * arbitrary pointer identifier).
     *
     * @see #AXIS_X
     */
    public final float getX() {
        return nativeGetAxisValue(mNativePtr, AXIS_X, 0, HISTORY_CURRENT);
    }
    
    /**
     * Returns the original raw X coordinate of this event.  For touch
     * events on the screen, this is the original location of the event
     * on the screen, before it had been adjusted for the containing window
     * and views.
     *
     * @see #getX(int)
     * @see #AXIS_X
     */
    public final float getRawX() {
        return nativeGetRawAxisValue(mNativePtr, AXIS_X, 0, HISTORY_CURRENT);
    }
  • TouchSlop : 定义系统能够识别的最小滑动距离
    在frameworks/base/core/res/res/values/config.xml中定义,默认8dp
    获取方式:ViewConfiguration.get(getContext()).getScaledTouchSlop(), 通过此常量做一些非滑动的过滤
    <!-- Base "touch slop" value used by ViewConfiguration as a
         movement threshold where scrolling should begin. -->
    <dimen name="config_viewConfigurationTouchSlop">8dp</dimen>

3.速度追踪、手势检测、滑动

  • VelocityTracker速度追踪
    在View的onTouchEvent方法中追踪点击事件的速度,传递MotionEvent
    实质上是计算时间间隔内的滑动像素数量
    VelocityTracker velocityTracker = VelocityTracker.obtain();
    velocityTracker.addMovement(event);
    velocityTracker.computeCurrentVelocity(1000);
    int xVelocity = (int)velocityTracker.getXVelocity();
    int yVelocity = (int)velocityTracker.getYVelocity();

velocityTracker.clear();
velocityTracker.recycle();

  • GestureDetector手势检测
    检测单机、滑动、长按、双击等行为

  • Scroller弹性滑动对象, smooth
    View的scrollTo 与 scrollBy 均为瞬间滑动,没有过度效果 (scrollBy内部调用scrollTo)
    Scroller的弹性滑动本质是通过时间来渐进滑动

4.View的滑动

1.view自带的scrollerTo/scrollerBy (瞬间的)
对内容进行移动, 内容在view的左边xScroll为正,内容在view的上面yScroll为正。

2.动画
View动画是对内容进行移动
属性动画是内view自身进行移动 (3.0以下的属性动画的实现本质为Viwe动画)

3.改变view的LayoutParams
对view自身进行移动

注意:
对view的内容进行变化,会存在点击位置不对的情况

5.弹性滑动/Smooth slide

1.Scroller + scrollTo

2.动画

3.使用延时策略(如Handler + scrollTo)

本质上都是通过时间渐进来达到视觉smooth滑动的效果,注意区分是view内容移动还是view本身移动

发布了37 篇原创文章 · 获赞 0 · 访问量 574

猜你喜欢

转载自blog.csdn.net/qq_37514242/article/details/103541233
今日推荐