Android - 创建一个锚定到视图的 Toast [英] Android - Create a Toast anchored to a View

查看:20
本文介绍了Android - 创建一个锚定到视图的 Toast的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个锚定到视图的吐司(即,出现在给定视图的旁边).

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

我试过了

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

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

but this creates it in an entire location entirely.

如果重要的话,我的视图是 TableRow 中的一个元素.

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

谢谢

我无法将 PopupWindow 用于此任务.

I can't use PopupWindow for this task.

推荐答案

我认为这个 教程 将帮助您实现您想要的:

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

这篇关于Android - 创建一个锚定到视图的 Toast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆