博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Using Touch Gestures 》Managing Touch Events in a ViewGroup
阅读量:4207 次
发布时间:2019-05-26

本文共 8732 字,大约阅读时间需要 29 分钟。

andling touch events in a  takes special care, because it's common for a  to have children that are targets for different touch events than the  itself. To make sure that each view correctly receives the touch events intended for it, override the  method.

Intercept Touch Events in a ViewGroup


The  method is called whenever a touch event is detected on the surface of a , including on the surface of its children. If returns true, the  is intercepted, meaning it will be not be passed on to the child, but rather to the  method of the parent.

The  method gives a parent the chance to see any touch event before its children do. If you return true from , the child view that was previously handling touch events receives an, and the events from that point forward are sent to the parent's  method for the usual handling.  can also return false and simply spy on events as they travel down the view hierarchy to their usual targets, which will handle the events with their own .

In the following snippet, the class MyViewGroup extends MyViewGroup contains multiple child views. If you drag your finger across a child view horizontally, the child view should no longer get touch events, and MyViewGroup should handle touch events by scrolling its contents. However, if you press buttons in the child view, or scroll the child view vertically, the parent shouldn't intercept those touch events, because the child is the intended target. In those cases,  should return false, and MyViewGroup's won't be called.

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 JUST determines whether we want to intercept the motion.         * If we return true, onTouchEvent will be called and we 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; // Do not intercept touch event, let the child handle it        }        switch (action) {
            case MotionEvent.ACTION_MOVE: {
                if (mIsScrolling) {
                    // We're currently scrolling, so yes, intercept the                     // touch event!                    return true;                }                // If the user has dragged her finger horizontally more than                 // the touch slop, start the scroll                // left as an exercise for the reader                final int xDiff = calculateDistanceX(ev);                 // Touch slop should be calculated using ViewConfiguration                 // constants.                if (xDiff > mTouchSlop) {
                    // Start scrolling!                    mIsScrolling = true;                    return true;                }                break;            }            ...        }        // In general, we don't want to intercept touch events. They should be         // handled by the child view.        return false;    }    @Override    public boolean onTouchEvent(MotionEvent ev) {
        // Here we actually handle the touch event (e.g. if the action is ACTION_MOVE,         // scroll this container).        // This method will only be called if the touch event was intercepted in         // onInterceptTouchEvent        ...    }}

Note that  also provides a  method. The  calls this method when a child does not want the parent and its ancestors to intercept touch events with.

Use ViewConfiguration Constants


The above snippet uses the current  to initialize a variable called mTouchSlop. You can use the  class to access common distances, speeds, and times used by the Android system.

"Touch slop" refers to the distance in pixels a user's touch can wander before the gesture is interpreted as scrolling. Touch slop is typically used to prevent accidental scrolling when the user is performing some other touch operation, such as touching on-screen elements.

Two other commonly used  methods are  and. These methods return the minimum and maximum velocity (respectively) to initiate a fling, as measured in pixels per second. For example:

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 occurred, do something    }...case MotionEvent.ACTION_UP: {
    ...    } if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity            && velocityY < velocityX) {
        // The criteria have been satisfied, do something    }}

Extend a Child View's Touchable Area


Android provides the  class to make it possible for a parent to extend the touchable area of a child view beyond the child's bounds. This is useful when the child has to be small, but should have a larger touch region. You can also use this approach to shrink the child's touch region if need be.

In the following example, an  is the "delegate view" (that is, the child whose touch area the parent will extend). Here is the layout file:

      

The snippet below does the following:

  • Gets the parent view and posts a  on the UI thread. This ensures that the parent lays out its children before calling the  method. The  method gets the child's hit rectangle (touchable area) in the parent's coordinates.
  • Finds the  child view and calls  to get the bounds of the child's touchable area.
  • Extends the bounds of the 's hit rectangle.
  • Instantiates a , passing in the expanded hit rectangle and the  child view as parameters.
  • Sets the  on the parent view, such that touches within the touch delegate bounds are routed to the child.
In its capacity as touch delegate for the 
 child view, the parent view will receive all touch events. If the touch event occurred within the child's hit rectangle, the parent will pass the touch event to the child for handling.

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 (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 should receive motion                // events.                TouchDelegate touchDelegate = new TouchDelegate(delegateArea,                         myButton);                     // Sets the TouchDelegate on the parent view, such that touches                 // within the touch delegate bounds are routed to the child.                if (View.class.isInstance(myButton.getParent())) {
                    ((View) myButton.getParent()).setTouchDelegate(touchDelegate);                }            }        });    }}

转载地址:http://vxlli.baihongyu.com/

你可能感兴趣的文章
python与正则表达式
查看>>
安装.Net Framework 4.7.2时出现“不受信任提供程序信任的根证书中终止”的解决方法
查看>>
input type=“button“与input type=“submit“的区别
查看>>
解决Github代码下载慢问题!
查看>>
1.idea中Maven创建项目及2.对idea中生命周期的理解3.pom文件夹下groupId、artifactId含义
查看>>
LeetCode-栈|双指针-42. 接雨水
查看>>
stdin,stdout,stderr详解
查看>>
Linux文件和设备编程
查看>>
文件描述符
查看>>
终端驱动程序:几个简单例子
查看>>
登录linux密码验证很慢的解决办法
查看>>
fcntl函数总结
查看>>
HTML条件注释
查看>>
Putty远程服务器的SSH经验
查看>>
内核态与用户态
查看>>
使用mingw(fedora)移植virt-viewer
查看>>
趣链 BitXHub跨链平台 (4)跨链网关“初介绍”
查看>>
C++ 字符串string操作
查看>>
MySQL必知必会 -- 了解SQL和MySQL
查看>>
MySQL必知必会 -- 使用MySQL
查看>>