Round button in android .. avoid clicking the “outside” button?

I created / tried to create a round button for android using the ImageButton widget. But since this type of button is considered as a square, and my png image is also regarded as a square with a transparent background, how can I avoid the user being able to click outside the round button? .. reason for now .. they can click in "corners" of the button, and this will still trigger the click event. Is there any special display layer that can be done in Photoshop or in any way change the radius of the image button so that it matches the "roundness" of my image .. or any ideas?

Thanks in advance! .. and sorry for the bad English ..

+7
source share
2 answers

Try the Pythagorean theorem and onTouch, a simple and easy way to do this.

public boolean inCircle(MotionEvent e, int radius, int x, int y) { int dx = ex - x; int dy = ey - y; double d = Math.sqrt((dx * dx) + (dy * dy)); if(d < radius) return true; return false; } 

x, y is the position of the circle, radius is the radius, e is the TouchEvent that you have.

 @Override public boolean onTouch(View arg0, MotionEvent arg1) { if(arg1.getAction() == MotionEvent.ACTION_DOWN){ if(inCircle(arg1, radius, xCircle, yCircle){ //do whatever you wanna do here } } return false; } 
+5
source

I used ImageView as the button for my circle, and I needed to make some changes to the @Daniel code to make it work the way I wanted. Here is my code:

 private boolean mStillDown = false; public boolean inCircle(MotionEvent e, float radius, float x, float y) { float dx = e.getX() - x; float dy = e.getY() - y; double d = Math.sqrt((dx * dx) + (dy * dy)); if(d < radius) return true; return false; } @Override public boolean onTouchEvent(MotionEvent event) { int action = event.getAction(); boolean inCircle = inCircle(event, getWidth()/2.0f, getWidth()/2.0f, getHeight()/2.0f); if(inCircle){ if(action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_POINTER_DOWN){ this.setPressed(true); mStillDown = true; }else if(action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP){ if(this.isPressed()){ this.performClick(); this.setPressed(false); mStillDown = false; } }else if(action == MotionEvent.ACTION_MOVE && mStillDown){ this.setPressed(true); } }else{ if(action == MotionEvent.ACTION_MOVE){ this.setPressed(false); }else if(action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP || action == MotionEvent.ACTION_OUTSIDE){ mStillDown = false; } } return true; } 

Hope this is helpful to someone.

+2
source

All Articles