Android Interview - View Event System

View event dispatch

public static dispatchTouchEvent(MotionEvent e){
    boolean consume = false;
    if(onInterceptTouchEvent(e)) {
        consume = onTouchEvent(e);
    } else {
        Consume = child.dispatchTouchEvent(e);    
    }
    return consume;
}
  • dispatchTouchEvent: Whether to consume the event. Determined by the onTouchEvent of the current View and the dispatchTouchEvent of the subordinate View
  • onInterceptTouchEvent: Whether to intercept the event. The external interception method is to intercept the event by rewriting the onInterceptTouchEvent of the parent container and returning true. After being intercepted, the View's onInterceptTouchEvent in the same event sequence will not be called again
  • onTouchEvent: Process the event and return whether to consume. Handle event priority onTouch > onTouchEvent > onClick. If the View does not consume the ACTION_DOWN event, that is, returns false, other events in the same event sequence, such as UP, MOVE, etc., will be handed over to the onTouchEvent of the parent container for processing.

View sliding

  • Using ScrollerTo/by: Only the content position of the View can be changed, but the position of the View in the layout cannot be changed
  • Use animation: View animation only manipulates images, while property animation can really change the layout position properties, which can deal with scenarios that need to deal with interaction.
  • Change LayoutParams: such as setting marginLeft, etc., it is more troublesome to implement but can also meet the needs of interaction.

View's elastic sliding

  • Scroller: View calls computeScroller in the onDraw method (we implement the elastic sliding code in it), it will obtain the current ScrollX and ScrollY through the Scroller object, calculate the new sliding distance through the passage of time, and whether the sliding stops, if it has not stopped, When sliding is achieved through scrollTo, postInvalidate is called for a second redraw, and so on.
  • Using Animation: Property Animation ValueAnimator
  • Use delay strategy: through Scrollto+Handler, or View's postDelayed

Swipe conflict resolution

  • External interception method: rewrite the onInterceptTouchEvent method of the parent container, write the interception logic, note that both ACTION_DOWN and ACTION_UP should return false, and the interception should be set in ACTION_MOVE.
  • Internal interception method: The child container consumes the event when it needs it, and does not hand it over to the parent container for processing. Proceed as follows:
First, override the dispatchTouchEvent of the child element
ACTION_DOWN: parent.requestDisallowInterceptionTouchEvent(false)
return super.dispatchTouchEvent(e);
Second, modify the onInterceptTouchEvent of the parent container
ACTION_DOWN: return false;
else return true;


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325730233&siteId=291194637