Skip to content Skip to sidebar Skip to footer

Implementing Swipe And Click In Android Button

I am new to android development, I tried to implement swipe (using Ontouch) for Activity and click events for the buttons in activity. If I swipe on top of buttons, swipe event is

Solution 1:

All you need is to process the difference between the coordinates while pressing and releasing the button.

Add this to the onCreate() of your activity:

protectedvoidonCreate(Bundle savedInstanceState) {
            final float len = getResources().getDisplayMetrics().densityDpi/6;
            OnTouch Listener controlButtonTouchListener=new View.OnTouchListener() {
                float initX;
                float initY;
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch(event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            initX = event.getX();
                            initY = event.getY();
                            break;
                        case MotionEvent.ACTION_UP:
                            initX -= event.getX(); //now has difference value
                            initY -= event.getY(); //now has difference valueif (initY > len) {
                                ((Button)v).setText("Swipe up");
                                //Toast.makeText(context,"Swipe up",Toast.LENGTH_SHORT).show();
                            } elseif(initY < -len) {
                                ((Button)v).setText("Swipe Down");
                                //Toast.makeText(context,"Swipe Down",Toast.LENGTH_SHORT).show();
                            } else {
                                if(initY < 0) initY = -initY;
                                if(initX < 0) initX = -initX;
                                if(initX <= len/4 && initY <= len/4) {
                                    ((Button)v).setText("Clicked");
                                }
                            }
                            break;
                    }
                    returntrue;
                }
            };
            findViewById(R.id.ClickSwipeButton).setOnTouchListener(controlButtonTouchListener);
        }

Post a Comment for "Implementing Swipe And Click In Android Button"