2

这些是遵循谷歌规格的FAB尺寸。 enter image description here如何仅允许点击浮动动作按钮的圈内?

在我的应用程序的情况下,我需要一个点击监听程序,点击FAB的圈子,避免单击在方形容器内(56x56)。

我已经想过在我的“整个”按钮中的每个onClick事件中获取X,Y,然后验证它是否在我的Fab的圆圈内,但是我想从此解决方法中逃脱,因为它可能导致准确性单击问题用不同的设备分辨率。

你有一个替代解决方案的任何想法?

在此先感谢。

编辑:

我实际上已经实现了这个JavaScript的解决方案转换在Java中
LINK
你认为我会永远得到设备的屏幕变化相同的准确度?

+0

你可以只使用两个按钮,放置一个在工厂的顶部... – Dportology

+0

我有一个自定义的椭圆形按钮同样的问题..的onclick在盒子发射反正...所以这不是只有浮动动作按钮我想,但在布局一般.. 它看起来像他们必须只是平方.. –

回答

0

我不认为有一种方法,实际上使可点击区域矩形之外。 如果你的圆圈是图像,你应该让你的浮动按钮的宽度和高度设置为wrap_content。任何方式你应该设置它的宽度和高度以匹配圆的直径。而处理该事件是这样的:

view.setOnTouchListener(new View.OnTouchListener() { 
           @Override 
           public boolean onTouch(View v, MotionEvent event) { 
            ViewGroup.LayoutParams layoutParams = v.getLayoutParams(); 
            float radius = layoutParams.width/2f; 
            float x = event.getX() - radius; 
            float y = event.getY() - radius; 
            if (isInCircle(radius, x, y)) { 
             if (event.getAction() == MotionEvent.ACTION_DOWN) { 
              // perform your action 
             } 
             return true; 
            } else { 
             return false; 
            } 
           } 

           private boolean isInCircle(float radius, float x, float y) { 
            if (Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)) < radius) { 
             //touch was performed inside the circle; 
             return true; 
            } else { 
             //touched ouside the circle 
             return false; 
            } 
           } 
          } 
    ); 

这将任何设备上工作,只要你的按钮在你绘制的圆紧紧包裹着。

如果不需要触摸事件陷入更深,您的浮动按钮下,当你错过了一圈,就可以避免一些重复计算是这样的:

view.setOnTouchListener(new View.OnTouchListener() { 
           @Override 
           public boolean onTouch(View v, MotionEvent event) { 
            if (event.getAction() == MotionEvent.ACTION_DOWN) { 
             ViewGroup.LayoutParams layoutParams = v.getLayoutParams(); 
             float radius = layoutParams.width/2f; 
             float x = event.getX() - radius; 
             float y = event.getY() - radius; 
             if (isInCircle(radius, x, y)) { 
              // perform your action 
             } 
            } 
            return true; 
           } 

           private boolean isInCircle(float radius, float x, float y) { 
            if (Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)) < radius) { 
             //touch was performed inside the circle; 
             return true; 
            } else { 
             //touched ouside the circle 
             return false; 
            } 
           } 
          } 
    ); 

请记住,这个工作你的按钮应该是严格的矩形。如果你想要一个按钮是一个椭圆,数学应该是不同的。