SoFunction
Updated on 2025-03-11

Exploring Android gesture event mechanism and optimization techniques

Types of gesture events

In Android, gesture events are divided into two types: touch events and motion events. Touch events include three types: press (DOWN), move (MOVE), and lift (UP). There are two types of motion events: scroll (SCROLL) and long press (LONG_PRESS).

Distribution mechanism of gesture events

When a user performs gesture operations, the Android system distributes gesture events to the currently active View or ViewGroup. The distribution mechanism of gesture events is completed by three methods: dispatchTouchEvent, onInterceptTouchEvent and onTouchEvent.

  • dispatchTouchEvent: This method is used to distribute gesture events, which passes gesture events to the currently active View or ViewGroup. If the currently active View or ViewGroup does not process the event, the event is passed to its parent View or ViewGroup until the event is processed or reaches the root View.
  • onInterceptTouchEvent: This method is used to intercept gesture events, which will be called before the dispatchTouchEvent method. If the currently active ViewGroup intercepts the event, the event will not be passed to its child View or ViewGroup.
  • onTouchEvent: This method is used to handle gesture events, which will be called after the dispatchTouchEvent method. If the currently active View or ViewGroup handles the event, the event will not be passed to its parent View or ViewGroup.

Handling process of gesture events

When gesture events are distributed to the currently active View or ViewGroup, they are processed according to the following process:

  • If the currently active View or ViewGroup does not have a child View, the event is processed directly.

  • If the currently active View or ViewGroup has a child View, the event is first passed to its child View for processing. If the child View does not process the event, the event will be passed back to the parent View or ViewGroup for processing.

  • If the currently active View or ViewGroup does not process the event, the event will be passed to its parent View or ViewGroup for processing. If the parent View or ViewGroup does not process the event, the event will be passed back to the ancestor View or ViewGroup for processing until the event is processed or reaches the root View.

Tips for optimizing user experience

In addition to understanding the principle of Android gesture event delivery, gesture events need to be handled reasonably according to specific application scenarios and needs to optimize the user experience. Here are some tips:

  • Sensitivity adjustment: The sensitivity of gesture events can be adjusted according to the user's gesture habits to improve the user's operating experience.
  • Feedback mechanism: When the user performs gesture operations, the user can be given feedback through vibration, sound, etc. to increase the user's operational perception.
  • Gesture recognition: Some specific gestures can be designed according to specific application scenarios to increase the operation efficiency of the application and the user's experience.

Example

The following sample code demonstrates how to implement gesture operations of sliding menus. This sample code uses ViewPager and Fragment to implement a sliding menu containing two Fragments on the left and right. In the main Activity, by setting the setOnTouchListener of ViewPager, listen to the user's gesture sliding event, and calculate the scaling ratio of the menu based on the sliding distance of the event, and then modify the size of the menu according to the scale.

class MainActivity : AppCompatActivity() {
    private val MIN_SLIDE_DISTANCE = 50 // Minimum distance for gesture sliding    private val MAX_WIDTH = 400 // Maximum menu width    private lateinit var viewPager: ViewPager
    private lateinit var menuLayout: View
    private lateinit var contentLayout: View
    private var startX = 0f
    private var menuWidth = 0
    private var currentWidth = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        (savedInstanceState)
        setContentView(.activity_main)
        viewPager = findViewById(.view_pager)
        menuLayout = findViewById(.menu_layout)
        contentLayout = findViewById(.content_layout)
         = MyPagerAdapter(supportFragmentManager)
        // Set the ViewPager's onTouchListener to listen for gesture sliding event         { _, event ->
            when () {
                MotionEvent.ACTION_DOWN -> {
                    startX = 
                    menuWidth = 
                    currentWidth = menuWidth
                }
                MotionEvent.ACTION_MOVE -> {
                    val distance = ( - startX).toInt()
                    if (distance > MIN_SLIDE_DISTANCE) {
                        // Calculate the telescopic width of the menu                        currentWidth = (MAX_WIDTH.toFloat(), (menuWidth + distance).toFloat()).toInt()
                        updateMenuLayout(currentWidth) // Update the size of menu and content area                    }
                }
                MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
                    if (currentWidth > menuWidth / 2) {
                        updateMenuLayout(MAX_WIDTH)
                    } else {
                        updateMenuLayout(menuWidth)
                    }
                }
            }
            false // Return false to indicate that this event is not consumed        }
    }
    /**
      * Update the width of menu and content area
      * @param width menu width
      */
    private fun updateMenuLayout(width: Int) {
        // Update the width of the menu         = width
        ()
        // Update the scaling ratio of the content area         = () / 
         = () / 
    }
    private inner class MyPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
        override fun getItem(position: Int): Fragment {
            return if (position == 0) {
                MenuFragment()
            } else {
                ContentFragment()
            }
        }
        override fun getCount(): Int {
            return 2
        }
    }
}

In this example code, the updateMenuLayout method is used to update the size of the menu and the scaling ratio of the content area, and to determine whether the menu needs to be scalable by judging whether the width of the menu is greater than half of the original width.

In addition, the processing of gesture events depends on other relevant knowledge points, such as event listening, view layout and drawing, etc. The relevant knowledge points will be expanded in detail later.

Summarize

Through the introduction of this article, we understand the principle of Android gesture event delivery, including the type of gesture event, distribution mechanism and processing flow. At the same time, we explored some tips for optimizing user experience. By applying these techniques and methods, we can improve the user experience of the application and make users more happy to use our application.

The above is the detailed content of exploring the mechanism and optimization techniques of Android gesture events. For more information about Android gesture events, please follow my other related articles!