Android - Create a view-bound toast

I want to create a toast that is attached to a view (i.e. will appear next to this view).

I tried

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

but it completely creates it entirely.

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

thanks

EDIT: I cannot use PopupWindow for this task.

+4
source share
1 answer

I think this Tutorial will help you 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, ie 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(); } }); 
+2
source

All Articles