Android 触摸点击效果

作者: 房嘻 | 来源:发表于2018-12-28 09:53 被阅读6次

    触摸点击效果基类代码如下:

    /**
     * 触摸点击基类
     */
    public abstract class BaseTouchListener implements View.OnTouchListener{
    
        protected boolean hasPerformedActionUp = false;
    
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                //按钮点击时触发点击效果
                actionDown(v);
                hasPerformedActionUp = true;
                v.getParent().requestDisallowInterceptTouchEvent(true);
            }
            if (event.getAction() == MotionEvent.ACTION_MOVE && hasPerformedActionUp) {
                float offsetX = event.getX();
                float offsetY = event.getY();
                //触摸区域超出view范围时取消点击效果
                if ((offsetX < 0 || offsetY < 0 || offsetX > v.getWidth() || offsetY > v.getHeight())) {
                    actionUp(v);
                    hasPerformedActionUp = false;
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                }
            }
            if (event.getAction() == MotionEvent.ACTION_UP && hasPerformedActionUp) {
                //按钮松开时取消效果
                actionUp(v);
            }
            return false;
        }
    
        //取消点击效果
        protected abstract void actionUp(View view);
    
        //点击效果(比如缩放,高亮,替换背景等等)
        protected abstract void actionDown(View view);
    }
    

    示例点击缩放代码

    public class TouchScaleListener extends BaseTouchListener {
    
        private float fromScale = 1.0F;
        private float toScale = 0.9F;
    
        public TouchScaleListener() {
        }
    
        public TouchScaleListener(float fromScale, float toScale) {
            this.fromScale = fromScale;
            this.toScale = toScale;
        }
    
        public TouchScaleListener(float toScale) {
            this.toScale = toScale;
        }
    
        @Override
        protected void actionDown(View view) {
            scaleXY(view, fromScale, toScale);
        }
    
        @Override
        protected void actionUp(View view) {
            scaleXY(view, toScale, fromScale);
        }
    
        private void scaleXY(View object, float fromValues, float toValues) {
            PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("scaleX", fromValues, toValues);
            PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("scaleY", fromValues, toValues);
            ObjectAnimator objectAnim = ObjectAnimator.ofPropertyValuesHolder(object, pvhX, pvhY);
            objectAnim.setDuration(25L);
            objectAnim.start();
        }
    }
    

    代码调用

    //按钮点击后缩小
    button.setOnTouchListener(new TouchScaleListener(0.90f));
    

    相关文章

      网友评论

        本文标题:Android 触摸点击效果

        本文链接:https://www.haomeiwen.com/subject/ucxslqtx.html