I´m creating an android project and I have a button and I want it to display a toast right below the button after the user clicks it. I don´t want to guess the coordinates of the button, so does anyone have a hint?
1) To GET the button's x-coordinates, call getLeft()
on your button. For the y-coordinates of the bottom of the button, call getTop()
and getHeight()
.
2) To PUT those coordinates into the Toast, use setGravity(Gravity.TOP|Gravity.LEFT, x, y)
.
3) To make this happen when the user clicks the button, do this in the button's onClick method.
public void makeToast(View view){
int x = view.getLeft();
int y = view.getTop() + 2*view.getHeight();
Toast toast = Toast.makeText(this, "see me", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.LEFT, x, y);
toast.show();
}
(Logically, I keep thinking it should be getTop + getHeight, but every time I tried that, the toast appeared on top of the button instead of below it. The factor of 2 made it work for a variety of heights.)
And in your xml:
<Button
<!-- put other attributes here -->
android:onClick="makeToast" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With