رویدادهای لمسی را در یک ViewGroup مدیریت کنید

روش نوشتن را امتحان کنید
Jetpack Compose ابزار رابط کاربری پیشنهادی برای اندروید است. در مورد حرکات در Compose اطلاعات کسب کنید.

مدیریت رویدادهای لمسی در یک ViewGroup نیاز به دقت ویژه‌ای دارد، زیرا معمولاً یک ViewGroup دارای فرزندانی است که اهداف رویدادهای لمسی متفاوتی نسبت به خود ViewGroup هستند. برای اطمینان از اینکه هر View به درستی رویدادهای لمسی در نظر گرفته شده برای آن را دریافت می‌کند، متد onInterceptTouchEvent() را بازنویسی کنید.

رهگیری رویدادهای لمسی در یک ViewGroup

متد onInterceptTouchEvent() هر زمان که یک رویداد لمسی در سطح یک ViewGroup ، از جمله در سطح فرزندان آن، شناسایی شود، فراخوانی می‌شود. اگر onInterceptTouchEvent() true را برگرداند، MotionEvent رهگیری می‌شود، به این معنی که به فرزند منتقل نمی‌شود، بلکه به متد onTouchEvent() از والد منتقل می‌شود.

متد onInterceptTouchEvent() به والد این فرصت را می‌دهد که رویدادهای لمسی را قبل از فرزندانش ببیند. اگر از onInterceptTouchEvent() true برگردانید، نمای فرزندی که قبلاً رویدادهای لمسی را مدیریت می‌کرد، یک ACTION_CANCEL دریافت می‌کند و رویدادها از آن نقطه به بعد برای مدیریت معمول به متد onTouchEvent() والد ارسال می‌شوند. onInterceptTouchEvent() همچنین می‌تواند false را برگرداند و رویدادها را در حین حرکت در سلسله مراتب نما به سمت اهداف معمول خود، که رویدادها را با onTouchEvent() خود مدیریت می‌کنند، جاسوسی کند.

در قطعه کد زیر، کلاس MyViewGroup ViewGroup ارث‌بری می‌کند. MyViewGroup شامل چندین نمای فرزند است. اگر انگشت خود را به صورت افقی روی یک نمای فرزند بکشید، نمای فرزند دیگر رویدادهای لمسی دریافت نمی‌کند و MyViewGroup با پیمایش محتویات آن، رویدادهای لمسی را مدیریت می‌کند. با این حال، اگر روی دکمه‌ها در نمای فرزند ضربه بزنید یا نمای فرزند را به صورت عمودی پیمایش کنید، والد آن رویدادهای لمسی را قطع نمی‌کند زیرا کودک هدف مورد نظر است. در این موارد، onInterceptTouchEvent() false را برمی‌گرداند و onTouchEvent() کلاس MyViewGroup فراخوانی نمی‌شود.

کاتلین

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.
        ...
    }
}

جاوا

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 همچنین متد requestDisallowInterceptTouchEvent() را ارائه می‌دهد. ViewGroup این متد را زمانی فراخوانی می‌کند که یک فرزند نمی‌خواهد والد و اجدادش رویدادهای لمسی را با onInterceptTouchEvent() رهگیری کنند.

رویدادهای ACTION_OUTSIDE را پردازش کنید

اگر یک ViewGroup یک MotionEvent با ACTION_OUTSIDE دریافت کند، این رویداد به طور پیش‌فرض به فرزندانش ارسال نمی‌شود. برای پردازش یک MotionEvent با ACTION_OUTSIDE ، یا dispatchTouchEvent(MotionEvent event) را برای ارسال به View مناسب لغو کنید یا آن را در Window.Callback مربوطه - مثلاً Activity - مدیریت کنید.

استفاده از ثابت‌های ViewConfiguration

قطعه کد قبلی ViewConfiguration فعلی برای مقداردهی اولیه متغیری به نام mTouchSlop استفاده می‌کند. می‌توانید از کلاس ViewConfiguration برای دسترسی به فواصل، سرعت‌ها و زمان‌های رایج مورد استفاده توسط سیستم اندروید استفاده کنید.

«شیب لمسی» به فاصله‌ای بر حسب پیکسل اشاره دارد که لمس کاربر می‌تواند قبل از اینکه حرکت به عنوان پیمایش تفسیر شود، منحرف شود. شیب لمسی معمولاً برای جلوگیری از پیمایش تصادفی هنگام انجام عملیات لمسی دیگر توسط کاربر، مانند لمس عناصر روی صفحه، استفاده می‌شود.

دو متد ViewConfiguration رایج دیگر getScaledMinimumFlingVelocity() و getScaledMaximumFlingVelocity() هستند. این متدها به ترتیب حداقل و حداکثر سرعت را برای شروع یک fling که بر حسب پیکسل در ثانیه اندازه‌گیری می‌شود، برمی‌گردانند. برای مثال:

کاتلین

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.
    }
}

جاوا

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.
    }
}

گسترش ناحیه قابل لمس نمای فرزند

اندروید کلاس TouchDelegate را ارائه می‌دهد تا به والد اجازه دهد ناحیه قابل لمس نمای فرزند را فراتر از مرزهای فرزند گسترش دهد. این زمانی مفید است که فرزند باید کوچک باشد اما به ناحیه لمسی بزرگتری نیاز دارد. همچنین می‌توانید از این رویکرد برای کوچک کردن ناحیه لمسی فرزند استفاده کنید.

در مثال زیر، یک ImageButton همان نمای _delegate_ است - یعنی فرزندی که ناحیه لمسی آن توسط والد امتداد می‌یابد. فایل طرح‌بندی به صورت زیر است:

<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 ارسال می‌کند. این کار تضمین می‌کند که والد قبل از فراخوانی متد getHitRect() فرزندان خود را طرح‌بندی می‌کند. متد getHitRect() مستطیل برخورد (یا ناحیه قابل لمس) فرزند را در مختصات والد دریافت می‌کند.
  • نمای فرزند ImageButton را پیدا می‌کند و getHitRect() را برای دریافت مرزهای ناحیه قابل لمس فرزند فراخوانی می‌کند.
  • مرزهای مستطیل برخوردِ نمای فرزندِ ImageButton را گسترش می‌دهد.
  • یک نمونه TouchDelegate ایجاد می‌کند و مستطیل باز شده‌ی مربوط به ضربه و نمای فرزند ImageButton را به عنوان پارامتر ارسال می‌کند.
  • TouchDelegate را روی نمای والد تنظیم می‌کند تا لمس‌های درون محدوده‌ی نماینده‌ی لمس به نمای فرزند هدایت شوند.

نمای والد به عنوان نماینده لمس برای نمای فرزند ImageButton ، تمام رویدادهای لمسی را دریافت می‌کند. اگر رویداد لمسی در مستطیل ضربه فرزند رخ دهد، والد رویداد لمسی را برای مدیریت به فرزند منتقل می‌کند.

کاتلین

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)
            }
        }
    }
}

جاوا

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);
                }
            }
        });
    }
}