How to make slide to unlock button in android

前端 未结 11 557
心在旅途
心在旅途 2020-12-23 18:05

Hi I want a button that should work as \'slide to unlock\' button of IOS

in short I want a button that has no click effect but can slide left to right while drag and

11条回答
  •  感情败类
    2020-12-23 18:25

    Starting from Oskar's answer (thanks for your contribute) i create a simple example project to manage Slide Button (horizontal and vertical) : https://github.com/rcaboni/AndroidSlideButton

    For a screen shot : https://raw.githubusercontent.com/rcaboni/AndroidSlideButton/master/screenshot.jpg

    This is the main method :

    public boolean onTouchEvent(MotionEvent event) {
        if (!isEnabled()) {
            return false;
        }
        if (orientation == ORIENTATION_HORIZONTAL) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                int x= (int) event.getX();
                int y= (int) event.getY();
                if (thumb.getBounds().contains((int) event.getX(), (int) event.getY())) {
                    super.onTouchEvent(event);
                } else
                    return false;
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                if (getProgress() > 70)
                    handleSlide();
    
                setProgress(0);
            } else
                super.onTouchEvent(event);
        }else{
            int i=0;
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        int x= (int) event.getX();
                        int y= (int) event.getY();
                        if (!thumb.getBounds().contains((int) event.getY(), (int) event.getX())) {
                            return false;
                        }
                    }
                case MotionEvent.ACTION_MOVE:
                    i=getMax() - (int) (getMax() * event.getY() / getHeight());
                    setProgress(100 - i);
                    onSizeChanged(getWidth(), getHeight(), 0, 0);
                    break;
                case MotionEvent.ACTION_UP:
                    i=getMax() - (int) (getMax() * event.getY() / getHeight());
                    if (i < 30) {
                        handleSlide();
                    }
                    setProgress(0);
                    onSizeChanged(getWidth(), getHeight(), 0, 0);
                    break;
    
                case MotionEvent.ACTION_CANCEL:
                    break;
            }
        }
        return true;
    }
    

    XML for vertical button :

    
        
        
        
    
    
    

    It's not a real complete widget because is composed from two view (TextView and SlideButton) into a Layout, but it's a easy configurable solution for Slide Button with text inside. I hope this is useful for someone.

提交回复
热议问题