Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Create a Toast anchored to a View

Tags:

android

toast

I want to create a toast that is anchored to a View (i.e., appears next a to given View).

I've tried

toast.setGravity(0, (int)v.getX(), (int)v.getY());

but this creates it in an entire location entirely.

If it matters, my view is an element in a TableRow.

Thanks

EDIT: I can't use PopupWindow for this task.

like image 398
Gal Avatar asked Dec 03 '12 12:12

Gal


1 Answers

I think this Tutorial will help you to achieve what you want:

public void onClick(View v) {
   int xOffset = 0;
   int yOffset = 0;
   Rect gvr = new Rect();

  View parent = (View) v.getParent();// v is the image,
    //parent is the rectangle holding it.

  if (parent.getGlobalVisibleRect(gvr)) {
        Log.v("image left", Integer.toString(gvr.left));
    Log.v("image right", Integer.toString(gvr.right));
    Log.v("image top", Integer.toString(gvr.top));
    Log.v("image bottom", Integer.toString(gvr.bottom));
    View root = v.getRootView();

        int halfwayWidth = root.getRight() / 2;
        int halfwayHeight = root.getBottom() / 2;
          //get the horizontal center
    int parentCenterX = ((gvr.right - gvr.left) / 2) + gvr.left;
     //get the vertical center
    int parentCenterY = (gvr.bottom - gvr.top) / 2 + gvr.top;

    if (parentCenterY <= halfwayHeight) {
       yOffset = -(halfwayHeight - parentCenterY);//this image is    above the center of gravity, i.e. the halfwayHeight
        } else {
        yOffset = parentCenterY - halfwayHeight;
        }
    if (parentCenterX < halfwayWidth) { //this view is left of center             xOffset = -(halfwayWidth - parentCenterX);    }   if (parentCenterX >= halfwayWidth) {
       //this view is right of center
       xOffset = parentCenterX - halfwayWidth;
    }
     }
       Toast toast = Toast.makeText(activity, altText, Toast.LENGTH_SHORT);
       toast.setGravity(Gravity.CENTER, xOffset, yOffset);
       toast.show();
       }
});
like image 54
K_Anas Avatar answered Nov 01 '22 13:11

K_Anas