Android View工作原理

1,039 阅读4分钟

做点笔记

工作流程

  • measure:计算view的宽和高,viewgroup会调用子view的onMesure方法,遍历整棵view树。
  • layout:确定view在父容器的放置位置,类似measure的方法。
  • draw:将view绘制在屏幕上,使用dispathDraw遍历view树。
    • 绘制背景
    • 绘制自己
    • 绘制子view
    • 绘制装饰

DecorView

顶级view,它包含一个LinearLayout,布局里面包含一个titlebar,还有一个id为content的viewgroup,你可以通过setContentView方法设置活动的内容view。

事件体系

  • MotionEvent:该对象记录了一次点击事件的x,y坐标。

事件分发机制

前面我们了解了view树,也就是你手机打开一个app,你面前的屏幕包含的是一颗view树,可以理解成它们重叠在了一起。当你点击屏幕时候,产生一个MotionEvent对象被activity对象分发给view树的根结点,调用它的dispatchTouchEvent方法,在这个方法中,会根据一些设置决定是否拦截这次事件,或是调用子view的dispatchTouchEvent方法。

  • dispatchTouchEvent:处理点击事件的分发逻辑。
  • onInterceptTouchEvent: 处理是否拦截事件逻辑,返回boolean值。
  • onTouchEvent: 处理点击事件逻辑。

当一个点击事件发生,该方法被调用,你可以重写该方法以拦截点击事件。

  public boolean dispatchTouchEvent(MotionEvent ev) {
      if (ev.getAction() == MotionEvent.ACTION_DOWN) {
          onUserInteraction();
      }
      if (getWindow().superDispatchTouchEvent(ev)) {
          return true;
      }
      return onTouchEvent(ev);
  }

getWindow().superDispatchTouchEvent(ev)将点击事件分发给Window对象。 继续往下发现PhoneWindow类无法直接访问。

找到一个解决方法,在sdk目录里面找到android.jar文件,加入libs文件夹中,add as library,双击shift查找PhoneWindow.class就可以看到源码了。

可以在PhoneWindow源码中看到其调用了DecorView对象中的superDispatchTouchEvent方法。

    public boolean superDispatchTouchEvent(MotionEvent event) {
        return mDecor.superDispatchTouchEvent(event);
    }

在DecorView类中可以找到它调用了dispatchTouchEvent方法,进入事件分发流程。

    public boolean superDispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }

在事件分发机制中,多个事件可以组成一个事件序列,事件分发机制就是对这个事件序列进行处理的一套代码。 一般一个事件序列以MotionEvent.ACTION_DOWN动作开始,以MotionEvent.ACTION_UP动作结束。

当点击事件为DOWN时,会重置TouchTarget状态。若前面事件被子View处理,会有一个参数mFirstTouchTarget指向该子View,在resetTouchState()方法中将mFirstTouchTarget重新复制为null。

  // Handle an initial down.
  if (actionMasked == MotionEvent.ACTION_DOWN) {
      // Throw away all previous state when starting a new touch gesture.
      // The framework may have dropped the up or cancel event for the previous gesture
      // due to an app switch, ANR, or some other state change.
      cancelAndClearTouchTargets(ev);
      resetTouchState();
  }

当点击事件为DOWN或者mFirstTouchTarget不为null,也就是说点击事件不为初始状态,简单分析一下就是,点击事件为初始状态,或者事件序列未结束都进入if条件语句中,进行分发,否则则设置布尔变量intercepted为false。用mGroupFlags计算是否拦截该事件。也就是说被拦截后,后序事件序列也由该view处理。

// Check for interception.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
        || mFirstTouchTarget != null) {
    final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
    if (!disallowIntercept) {
        intercepted = onInterceptTouchEvent(ev);
        ev.setAction(action); // restore action in case it was changed
    } else {
        intercepted = false;
    }
} else {
    // There are no touch targets and this action is not an initial down
    // so this view group continues to intercept touches.
    intercepted = true;
}

不拦截事件时进入这,遍历子节点,找到可以consume该事件的view。可以看到若点击事件坐标落在子元素区域

for (int i = childrenCount - 1; i >= 0; i--) {
    final int childIndex = getAndVerifyPreorderedIndex(
            childrenCount, i, customOrder);
    final View child = getAndVerifyPreorderedView(
            preorderedList, children, childIndex);
    if (!child.canReceivePointerEvents()
            || !isTransformedTouchPointInView(x, y, child, null)) {
        continue;
    }

    newTouchTarget = getTouchTarget(child);
    if (newTouchTarget != null) {
        // Child is already receiving touch within its bounds.
        // Give it the new pointer in addition to the ones it is handling.
        newTouchTarget.pointerIdBits |= idBitsToAssign;
        break;
    }

    resetCancelNextUpFlag(child);
    if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
        // Child wants to receive touch within its bounds.
        mLastTouchDownTime = ev.getDownTime();
        if (preorderedList != null) {
            // childIndex points into presorted list, find original index
            for (int j = 0; j < childrenCount; j++) {
                if (children[childIndex] == mChildren[j]) {
                    mLastTouchDownIndex = j;
                    break;
                }
            }
        } else {
            mLastTouchDownIndex = childIndex;
        }
        mLastTouchDownX = ev.getX();
        mLastTouchDownY = ev.getY();
        newTouchTarget = addTouchTarget(child, idBitsToAssign);
        alreadyDispatchedToNewTouchTarget = true;
        break;
    }

    // The accessibility focus didn't handle the event, so clear
    // the flag and do a normal dispatch to all children.
    ev.setTargetAccessibilityFocus(false);
}

我们可以在dispatchTransformedTouchEvent中找到下面这段代码,子元素的dispatchTouchEvent方法被调用,事件分发结束。

  event.setAction(MotionEvent.ACTION_CANCEL);
  if (child == null) {
      handled = super.dispatchTouchEvent(event);
  } else {
      handled = child.dispatchTouchEvent(event);
  }
  event.setAction(oldAction);
  return handled;