Esmatullah Adel Esmatullah Adel - 3 months ago 26
Android Question

How to change the position of fab with onTouchListener?

I am using Floating Action Button. I want to change the position of fab when the user touch the fab and drag it. I am using onTouchListener but it does not move the fab well.
Here is my code:

final FloatingActionButton fabButton = new FloatingActionButton.Builder(this)
.withDrawable(getResources().getDrawable(R.drawable.fab))
.withButtonColor(Color.WHITE)
.withGravity(Gravity.BOTTOM | Gravity.RIGHT)
.withMargins(0, 0, 16, 16)
.create();
fabButton.setAlpha(0.6f);
fabButton.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
fabButton.setX(event.getX());
fabButton.setY(event.getY());

return false;
}
});


thanks from any suggestions in advance...

Answer

The problem was in return false; If listener returns false on finger down event, then move event is ignored, in simple words. Try 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;
        }
    });

Also, as x and y are coordinates of left top corner of view, you probably don't want to set x and y of touch as these coordinates. Instead, you should calculate delta of movement and increase initial coordinates of fab, as I specified in the snippet above

Comments