1

I have an ImageButton that I need aligned to the bottom of the screen, and when I click and drag it, it moves with my finger by a certain distance, beyond which it will not move further from the origin but continue following the direction my finger is from the origin.

When I let go, the button has to slide back to the origin.

What I have managed to do so far is to have the button follow my finger via this answer: Moving buttons via Touch

However, how should I get the origin of the button at initialization for it to bounce back after I release?


Originally I implemented the alignment of the button by having a android:layout_gravity="center|bottom" to place it at the bottom, but it somehow messes with the position of the button relative to my finger (It follows my finger movements but it's off center).

Hence, I used mButton.setY() and mButton.setX() to place it at the bottom of the screen, but it seemed hackish to use the screen dimensions to place it. Can't think of a better way.

Community
  • 1
  • 1
Quorrin
  • 99
  • 1
  • 3
  • 10

1 Answers1

1

You can set the width and height of your layout in XML using layout_width and layout_height.

Then in your MainActivity, instantiate the layout (I will use LinearLayout as an example) and get its width and height.

LinearLayout l = (LinearLayout)findviewbyid(R.id.l1);
int height = l.getHeight();
int width = l.getWidth();

Now, whenever you release the button, you can set your its position in the following way:

mButton.setY(height - 50)

This will position the ImageButton 50 pixels above the bottom of your layout. You can also set the x position of the button as you want in the same way. Also, you should probably store height - 50 as a global variable (origin) that you can call from anywhere in your code.

Kairat
  • 790
  • 3
  • 7