How to make slide to unlock button in android

前端 未结 11 572
心在旅途
心在旅途 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:30

    I started out with the example that Jignesh Ansodariya posted, but as Aerrow points out, the user can click anywhere on the SeekBar to unlock. That makes it quite unusable, since the point with having a slide button is that accidental clicks should be ignored. My solution was to create a subclass of SeekBar, like this:

    public class SlideButton extends SeekBar {
    
        private Drawable thumb;
        private SlideButtonListener listener;
    
        public SlideButton(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        @Override
        public void setThumb(Drawable thumb) {
            super.setThumb(thumb);
            this.thumb = thumb;
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                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);
    
            return true;
        }
    
        private void handleSlide() {
            listener.handleSlide();
        }
    
        public void setSlideButtonListener(SlideButtonListener listener) {
            this.listener = listener;
        }   
    }
    
    public interface SlideButtonListener {
        public void handleSlide();
    }
    

    XML:

            
            
    

    And finally the code inside my Activity:

        ((SlideButton) findViewById(R.id.unlockButton)).setSlideButtonListener(new SlideButtonListener() {  
            @Override
            public void handleSlide() {
                unlockScreen();
            }
        });
    

提交回复
热议问题