gpt4 book ai didi

Android - 创建锚定到 View 的 Toast

转载 作者:太空宇宙 更新时间:2023-11-03 10:24:59 24 4
gpt4 key购买 nike

我想创建一个锚定到 View 的 toast(即,出现在给定 View 的旁边)。

我试过了

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

但这会完全在整个位置创建它。

如果重要的话,我的 View 是 TableRow 中的一个元素。

谢谢

编辑:我不能将 PopupWindow 用于此任务。

最佳答案

我觉得这个Tutorial将帮助你实现你想要的:

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();
}
});

关于Android - 创建锚定到 View 的 Toast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13683582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com