我为 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();