我想创建一个锚定到视图的吐司(即,出现在给定视图旁边)。
我试过了
toast.setGravity(0, (int)v.getX(), (int)v.getY());
但这完全在整个位置创建它。
如果重要的话,我的视图是 TableRow 中的一个元素。
谢谢
编辑:我不能使用 PopupWindow 来完成这项任务。
我认为本教程将帮助您实现您想要的:
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();
}
});