Thursday, 28 August 2014

Handling custom touch events in Android Apps

Custom view controls may require non-standard touch event behavior. For example, a custom control may use the onTouchEvent(MotionEvent) listener method to detect the ACTION_DOWN and ACTION_UP events and trigger a special click event. In order to maintain compatibility with accessibility services, the code that handles this custom click event must do the following:
  1. Generate an appropriate AccessibilityEvent for the interpreted click action.
  2. Enable accessibility services to perform the custom click action for users who are not able to use a touch screen.
To handle these requirements in an efficient way, your code should override the performClick() method, which must call the super implementation of this method and then execute whatever actions are required by the click event. When the custom click action is detected, that code should then call your performClick() method. The following code example demonstrates this pattern.
classCustomTouchViewextendsView{

    publicCustomTouchView(Context context){
        super(context);
    }

    boolean mDownTouch =false;

    @Override
    publicboolean onTouchEvent(MotionEventevent){
        super.onTouchEvent(event);

        // Listening for the down and up touch events
        switch(event.getAction()){
            caseMotionEvent.ACTION_DOWN:
                mDownTouch =true;
                returntrue;

            caseMotionEvent.ACTION_UP:
                if(mDownTouch){
                    mDownTouch =false;
                    performClick();// Call this method to handle the response, and
                                    // thereby enable accessibility services to
                                    // perform this action for a user who cannot
                                    // click the touchscreen.
                    returntrue;
                }
        }
        returnfalse;// Return false for other touch events
    }

    @Override
    publicboolean performClick(){
        // Calls the super implementation, which generates an AccessibilityEvent
        // and calls the onClick() listener on the view, if any
        super.performClick();

        // Handle the action for the custom click here

        returntrue;
    }}
The pattern shown above makes sure that the custom click event is compatible with accessibility services by using the performClick() method to both generate an accessibility event and provide an entry point for accessibility services to act on behalf of a user to perform this custom click event.

No comments:

Post a Comment