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?

Upvotes: 6

Views: 3001

Answers (3)

LEGEND MORTAL
LEGEND MORTAL

Reputation: 336

no need to use toast instead use Tooltip

see here > official documentation of tooltip

Upvotes: 0

AJ Macdonald
AJ Macdonald

Reputation: 436

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" />

Upvotes: 12

Robert Rowntree
Robert Rowntree

Reputation: 6289

Adjustments on the "setGravity" line...

code below should do:

       View v = findViewById(R.id.youButtnView);                    
        int location[]=new int[2];
        v.getLocationOnScreen(location);
   Toast toast=Toast.makeText(getApplicationContext(), 
    "Your message", Toast.LENGTH_LONG);
    toast.setGravity(Gravity.TOP|Gravity.LEFT,v.getRight()-25, location[1]-10);
    toast.show();

Upvotes: 0

Related Questions