Search code examples
androidandroid-layoutfloating-action-button

How to set position of Fab button to the left or right edge of the Coordinator Layout in Android


I am using this code:

fabButton.setOnTouchListener(new View.OnTouchListener() {

    float x, y;
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()){

            case MotionEvent.ACTION_MOVE:

                fabButton.setX(fabButton.getX() + (event.getX() - x));
                fabButton.setY(fabButton.getY() + (event.getY() - y));
                return true;
            case MotionEvent.ACTION_DOWN:
                x = event.getX();
                y = event.getY();
                return true;
        }

        return false;
    }
});

now I want to set the position of Fab button to right most or left most edge of Coordinator layout.

May be

if (xCoordinate < screen center)
{
   align Fab  button to the Right screen
}

if (xCoordinate > Screen Center)
{
   align Fab button to the left of the screen
}

I don't know how to manage this thing.


Solution

  • I manage to make this, Now its Correct way to position Fab Button left or right

    Display display = getWindowManager().getDefaultDisplay();
                        Point size = new Point();
                        display.getSize(size);
                        CoordinatorLayout.LayoutParams p = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
                        p.setBehavior(new FloatingActionButton.Behavior());
                        fab.setLayoutParams(p);
                        if(fab.getX() < 0)
                        {
                            fab.setX(2.0f);
                        }
                        if(fab.getX() > size.x)
                        {
                            fab.setX(size.x -1);
                        }
    
                        if(fab.getY() < 0)
                        {
                            fab.setY(4.0f);
                        }
                        if(fab.getY() > size.y)
                        {
                            fab.setY(size.y -1);
                        }
    
                        if(fab.getX() < size.x/2)
                        {
                            fab.setX((5*size.x/100));
                        }else
                        {
                            fab.setX(size.x - (12*size.x/100));
                        }
    

    Its working