ניהול אירועי מגע ב-ViewGroup

אפשר לנסות את הדרך של כתיבת הודעה
‫Jetpack Compose היא ערכת הכלים המומלצת לבניית ממשק משתמש ב-Android. מידע על תנועות בכתיבה.

כשמטפלים באירועי מגע ב-ViewGroup, צריך לנקוט משנה זהירות כי בדרך כלל ל-ViewGroup יש צאצאים שהם יעדים לאירועי מגע שונים מאלה של ViewGroup עצמו. כדי לוודא שכל תצוגה מקבלת בצורה נכונה את אירועי המגע שמיועדים לה, צריך לבטל את השיטה onInterceptTouchEvent().

יירוט אירועי מגע ב-ViewGroup

השיטה onInterceptTouchEvent() נקראת בכל פעם שמזוהה אירוע מגע ב-ViewGroup, כולל בצאצאים שלו. אם הפונקציה onInterceptTouchEvent() מחזירה true, הפונקציה MotionEvent перехватывается, כלומר היא לא מועברת אל הצאצא אלא אל השיטה onTouchEvent() של האב.

השיטה onInterceptTouchEvent() מאפשרת להורה לראות אירועי מגע לפני שהילדים רואים אותם. אם מחזירים true מ-onInterceptTouchEvent(), תצוגת הילד שטיפלה קודם באירועי מגע מקבלת ACTION_CANCEL, והאירועים מאותה נקודה ואילך נשלחים לשיטה onTouchEvent() של ההורה לטיפול הרגיל. ‫onInterceptTouchEvent() יכול גם להחזיר את false ולעקוב אחרי אירועים כשהם עוברים בהיררכיית התצוגה אל היעדים הרגילים שלהם, שמטפלים באירועים באמצעות onTouchEvent() משלהם.

בקטע הקוד הבא, המחלקה MyViewGroup מרחיבה את ViewGroup. ‫MyViewGroup מכיל מספר תצוגות צאצא. אם גוררים את האצבע לרוחב תצוגת הצאצא, תצוגת הצאצא לא מקבלת יותר אירועי מגע, ו-MyViewGroup מטפל באירועי מגע על ידי גלילת התוכן שלו. עם זאת, אם מקישים על לחצנים בתצוגת הצאצא או גוללים את תצוגת הצאצא באופן אנכי, רכיב ההורה לא מיירט את אירועי המגע האלה כי הצאצא הוא היעד המיועד. במקרים כאלה, הפונקציה onInterceptTouchEvent() מחזירה false, והפונקציה onTouchEvent() של המחלקה MyViewGroup לא נקראת.

Kotlin

class MyViewGroup @JvmOverloads constructor(
        context: Context,
        private val mTouchSlop: Int = ViewConfiguration.get(context).scaledTouchSlop
) : ViewGroup(context) {
    ...
    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        // This method only determines whether you want to intercept the motion.
        // If this method returns true, onTouchEvent is called and you can do
        // the actual scrolling there.
        return when (ev.actionMasked) {
            // Always handle the case of the touch gesture being complete.
            MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
                // Release the scroll.
                mIsScrolling = false
                false // Don't intercept the touch event. Let the child handle it.
            }
            MotionEvent.ACTION_MOVE -> {
                if (mIsScrolling) {
                    // You're currently scrolling, so intercept the touch event.
                    true
                } else {

                    // If the user drags their finger horizontally more than the
                    // touch slop, start the scroll.

                    // Left as an exercise for the reader.
                    val xDiff: Int = calculateDistanceX(ev)

                    // Touch slop is calculated using ViewConfiguration constants.
                    if (xDiff > mTouchSlop) {
                        // Start scrolling!
                        mIsScrolling = true
                        true
                    } else {
                        false
                    }
                }
            }
            ...
            else -> {
                // In general, don't intercept touch events. The child view
                // handles them.
                false
            }
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        // Here, you actually handle the touch event. For example, if the action
        // is ACTION_MOVE, scroll this container. This method is only called if
        // the touch event is intercepted in onInterceptTouchEvent.
        ...
    }
}

Java

public class MyViewGroup extends ViewGroup {

    private int mTouchSlop;
    ...
    ViewConfiguration vc = ViewConfiguration.get(view.getContext());
    mTouchSlop = vc.getScaledTouchSlop();
    ...
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        // This method only determines whether you want to intercept the motion.
        // If this method returns true, onTouchEvent is called and you can do
        // the actual scrolling there.

        final int action = MotionEventCompat.getActionMasked(ev);

        // Always handle the case of the touch gesture being complete.
        if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
            // Release the scroll.
            mIsScrolling = false;
            return false; // Don't intercept touch event. Let the child handle it.
        }

        switch (action) {
            case MotionEvent.ACTION_MOVE: {
                if (mIsScrolling) {
                    // You're currently scrolling, so intercept the touch event.
                    return true;
                }

                // If the user drags their finger horizontally more than the
                // touch slop, start the scroll.

                // Left as an exercise for the reader.
                final int xDiff = calculateDistanceX(ev);

                // Touch slop is calculated using ViewConfiguration constants.
                if (xDiff > mTouchSlop) {
                    // Start scrolling.
                    mIsScrolling = true;
                    return true;
                }
                break;
            }
            ...
        }

        // In general, don't intercept touch events. The child view handles them.
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        // Here, you actually handle the touch event. For example, if the
        // action is ACTION_MOVE, scroll this container. This method is only
        // called if the touch event is intercepted in onInterceptTouchEvent.
        ...
    }
}

שימו לב ש-ViewGroup מספק גם method‏ requestDisallowInterceptTouchEvent(). ‫ViewGroup קורא לשיטה הזו כשילד לא רוצה שהורה והאבות הקדמונים שלו ייעדו אירועי מגע עם onInterceptTouchEvent().

עיבוד אירועים מסוג ACTION_OUTSIDE

אם רכיב ViewGroup מקבל אירוע MotionEvent עם ACTION_OUTSIDE, האירוע לא מועבר לרכיבי הצאצא שלו כברירת מחדל. כדי לעבד MotionEvent באמצעות ACTION_OUTSIDE, צריך לבטל את ההגדרה של dispatchTouchEvent(MotionEvent event) כדי לשלוח את הבקשה אל View המתאים, או לטפל בה ב-Window.Callback הרלוונטי, לדוגמה, Activity.

שימוש בקבועים של ViewConfiguration

בקטע הקוד הקודם נעשה שימוש בערך הנוכחי של ViewConfiguration כדי לאתחל משתנה בשם mTouchSlop. אפשר להשתמש במחלקה ViewConfiguration כדי לגשת למרחקים, למהירויות ולזמנים נפוצים שמשמשים את מערכת Android.

המונח "מרחק תנועה" מתייחס למרחק בפיקסלים שהאצבע של המשתמש יכולה לנוע לפני שהמערכת מפרשת את התנועה כמחווה של גלילה. בדרך כלל משתמשים ב-touch slop כדי למנוע גלילה מקרית כשהמשתמש מבצע פעולת מגע אחרת, כמו נגיעה ברכיבים במסך.

שתי שיטות נוספות נפוצות של ViewConfiguration הן getScaledMinimumFlingVelocity() ו-getScaledMaximumFlingVelocity(). השיטות האלה מחזירות את המהירות המינימלית והמקסימלית, בהתאמה, כדי להתחיל תנועת החלקה שנמדדת בפיקסלים לשנייה. לדוגמה:

Kotlin

private val vc: ViewConfiguration = ViewConfiguration.get(context)
private val mSlop: Int = vc.scaledTouchSlop
private val mMinFlingVelocity: Int = vc.scaledMinimumFlingVelocity
private val mMaxFlingVelocity: Int = vc.scaledMaximumFlingVelocity
...
MotionEvent.ACTION_MOVE -> {
    ...
    val deltaX: Float = motionEvent.rawX - mDownX
    if (Math.abs(deltaX) > mSlop) {
        // A swipe occurs, do something.
    }
    return false
}
...
MotionEvent.ACTION_UP -> {
    ...
    if (velocityX in mMinFlingVelocity..mMaxFlingVelocity && velocityY < velocityX) {
        // The criteria are satisfied, do something.
    }
}

Java

ViewConfiguration vc = ViewConfiguration.get(view.getContext());
private int mSlop = vc.getScaledTouchSlop();
private int mMinFlingVelocity = vc.getScaledMinimumFlingVelocity();
private int mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
...
case MotionEvent.ACTION_MOVE: {
    ...
    float deltaX = motionEvent.getRawX() - mDownX;
    if (Math.abs(deltaX) > mSlop) {
        // A swipe occurs, do something.
    }
...
case MotionEvent.ACTION_UP: {
    ...
    } if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity
            && velocityY < velocityX) {
        // The criteria are satisfied, do something.
    }
}

הרחבת האזור שאפשר לגעת בו בתצוגת צאצא

ב-Android יש את המחלקה TouchDelegate שמאפשרת להורה להרחיב את האזור שאפשר לגעת בו בתצוגת צאצא מעבר לגבולות של הצאצא. האפשרות הזו שימושית כשצריך להקטין את הילד אבל הוא צריך אזור מגע גדול יותר. אפשר להשתמש בגישה הזו גם כדי להקטין את אזור המגע של הילד או הילדה.

בדוגמה הבאה, ImageButton הוא _delegate view_ – כלומר, הצאצא שאזור המגע שלו מורחב על ידי ההורה. זהו קובץ הפריסה:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/parent_layout"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     tools:context=".MainActivity" >

     <ImageButton android:id="@+id/button"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:background="@null"
          android:src="@drawable/icon" />
</RelativeLayout>

קטע הקוד הבא משלים את המשימות האלה:

  • מקבל את התצוגה להורה ומפרסם Runnable בשרשור UI. כך מוודאים שהרכיב ההורה יציג את רכיבי הצאצא לפני הפעלת ה-method‏ getHitRect(). השיטה getHitRect() מחזירה את מלבן ההקשה (או את האזור שאפשר לגעת בו) של הרכיב המשני בקואורדינטות של הרכיב הראשי.
  • מחפש את התצוגה של ImageButton child וקורא ל-getHitRect() כדי לקבל את הגבולות של האזור שניתן לגעת בו ב-child.
  • מרחיב את הגבולות של מלבן ההקשה של תצוגת הצאצא ImageButton.
  • יוצר מופע של TouchDelegate, ומעביר את המלבן המורחב של ההיט ואת תצוגת הצאצא ImageButton כפרמטרים.
  • הגדרת TouchDelegate בתצוגת ההורה כך שהקשות בגבולות של נציג ההקשה ינותבו אל הצאצא.

בתור נציג המגע של תצוגה לילדים ImageButton, תצוגה להורה מקבלת את כל אירועי המגע. אם אירוע המגע מתרחש בתוך מלבן הפגיעה של רכיב הצאצא, רכיב האב מעביר את אירוע המגע לרכיב הצאצא לטיפול.

Kotlin

public class MainActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Post in the parent's message queue to make sure the parent lays out
        // its children before you call getHitRect().
        findViewById<View>(R.id.parent_layout).post {
            // The bounds for the delegate view, which is an ImageButton in this
            // example.
            val delegateArea = Rect()
            val myButton = findViewById<ImageButton>(R.id.button).apply {
                isEnabled = true
                setOnClickListener {
                    Toast.makeText(
                            this@MainActivity,
                            "Touch occurred within ImageButton touch region.",
                            Toast.LENGTH_SHORT
                    ).show()
                }

                // The hit rectangle for the ImageButton.
                getHitRect(delegateArea)
            }

            // Extend the touch area of the ImageButton beyond its bounds on the
            // right and bottom.
            delegateArea.right += 100
            delegateArea.bottom += 100

            // Set the TouchDelegate on the parent view so that touches within
            // the touch delegate bounds are routed to the child.
            (myButton.parent as? View)?.apply {
                // Instantiate a TouchDelegate. "delegateArea" is the bounds in
                // local coordinates of the containing view to be mapped to the
                // delegate view. "myButton" is the child view that receives
                // motion events.
                touchDelegate = TouchDelegate(delegateArea, myButton)
            }
        }
    }
}

Java

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Get the parent view.
        View parentView = findViewById(R.id.parent_layout);

        parentView.post(new Runnable() {
            // Post in the parent's message queue to make sure the parent lays
            // out its children before you call getHitRect().
            @Override
            public void run() {
                // The bounds for the delegate view, which is an ImageButton in
                // this example.
                Rect delegateArea = new Rect();
                ImageButton myButton = (ImageButton) findViewById(R.id.button);
                myButton.setEnabled(true);
                myButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(MainActivity.this,
                                "Touch occurred within ImageButton touch region.",
                                Toast.LENGTH_SHORT).show();
                    }
                });

                // The hit rectangle for the ImageButton.
                myButton.getHitRect(delegateArea);

                // Extend the touch area of the ImageButton beyond its bounds on
                // the right and bottom.
                delegateArea.right += 100;
                delegateArea.bottom += 100;

                // Instantiate a TouchDelegate. "delegateArea" is the bounds in
                // local coordinates of the containing view to be mapped to the
                // delegate view. "myButton" is the child view that receives
                // motion events.
                TouchDelegate touchDelegate = new TouchDelegate(delegateArea,
                        myButton);

                // Set the TouchDelegate on the parent view so that touches
                // within the touch delegate bounds are routed to the child.
                if (View.class.isInstance(myButton.getParent())) {
                    ((View) myButton.getParent()).setTouchDelegate(touchDelegate);
                }
            }
        });
    }
}