【问题标题】:Android Position Custom Toast Above User's touchAndroid将自定义吐司置于用户触摸之上
【发布时间】:2013-07-27 02:00:01
【问题描述】:

我为 Toast 消息创建了自定义背景。我使用 MotionEvent 来抓取 rawX 和 rawY,然后显示用户点击的 Toast。唯一的问题是 Toast 的顶部出现在用户接触点下方而不是上方。所以基本上,如果我在展示 Toast 时知道它的高度,我可以将它向上移动 Y 轴,这样它就会在用户点击 x,y 点的上方。但是,您无法在绘制之前获得 Toast 的高度。还有其他方法可以通过重力参数获得正确的位置吗?

        //Retrieve the layout inflator
        LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //Assign the custom layout to view
        //Parameter 1 - Custom layout XML
        //Parameter 2 - Custom layout ID present in linearlayout tag of XML
        View layout = inflater.inflate(R.layout.popup_toast,
                    (ViewGroup) llayParent.findViewById(R.id.popToastLayoutRoot));


        m_tv_what = (TextView)layout.findViewById(R.id.ptextWhat);
        m_tv_priority = (TextView)layout.findViewById(R.id.ptextPrior);
        m_tv_where  = (TextView)layout.findViewById(R.id.ptextWhere);
        m_tv_notes = (TextView)layout.findViewById(R.id.ptextNotes);

        m_tv_what.setText(row.sSubject);
         switch((int)row.lPriority){
            case 3:
                m_tv_priority.setText("low");
            break;

            case 2:
                m_tv_priority.setText("medium");
            break;

            case 1:
                m_tv_priority.setText("HIGH");
            break;

         }
         m_tv_where.setText(row.sWhere);
         m_tv_notes.setText(row.sDescription);



        //Return the application context
        Toast toast = new Toast(ctx);
        //Set toast gravity to bottom

             //the height is 0 of course , because it has not been drawn yet
             //any way to get height?
            int height =layout.getHeight();

             toast.setGravity(Gravity.TOP|Gravity.LEFT ,(int)x, (int)y );
        //Set toast duration
        toast.setDuration(Toast.LENGTH_LONG);
        //Set the custom layout to Toast
        toast.setView(layout);
        //Display toast
        toast.show();

【问题讨论】:

    标签: android positioning toast


    【解决方案1】:

    你需要使用 setGravity() 方法,首先获取用户触摸的坐标,然后尝试这样的操作:

    toast.setGravity(Gravity.TOP|Gravity.LEFT, x, y);
    

    其中 x 和 y 是从左上角开始的 x 和 y 坐标中的偏移量,Gravity 是一个常数。

    【讨论】:

    • 我已经在使用 SetGravity() 查看我的代码...但它定位在用户点击点下方,我想将它定位在用户点击点上方,换句话说,位于toast 就在用户点击的 y 位置
    • 好吧,只是修改偏移量,这正是它的目的
    • 这就是问题所在,我不知道要偏移多少,因为屏幕分辨率不同,它不能是静态值-因此它必须是动态的,我需要的是高度在我展示它的时候吐司,我不知道如何得到它。
    【解决方案2】:

    我最终使用了具有透明背景的 Activity,而不是 toast。活动的内容视图 (RelativeLayout) 包含我为 toast 设置的相同视图。然后,我动态设置 RelativeLayout 的 padding_top,将其向下推,使 RelativeLayout 的底部正好位于用户触摸的位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-15
      • 2012-07-02
      • 2015-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多