Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Display a toast right below a view?

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?

like image 820
Fabio Phillip Rocha Marques Avatar asked Jun 25 '14 22:06

Fabio Phillip Rocha Marques


1 Answers

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" />
like image 167
AJ Macdonald Avatar answered Sep 20 '22 10:09

AJ Macdonald