试试这个:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
标准的 Toast 通知出现在屏幕底部附近,水平居中。您可以使用setGravity(int, int, int) 方法更改此位置。这接受三个参数:重力常数、x 位置偏移和 y 位置偏移。
例如,如果您决定吐司应该出现在左上角,您可以这样设置重力:
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
如果要将位置向右微移,请增加第二个参数的值。要向下微调,请增加最后一个参数的值。
官方文档来源Here
对于自定义Toast,请检查here
自定义位置请关注this
编辑:要在特定的View 上建立位置,试试这个:
此代码在您的 onCreate() 方法中
editText1 = (EditText)rootView.findViewById(R.id.editText1);
button1 = (Button)rootView.findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
makeToast("Hello", editText1);
}
});
并添加这个makeToast(String,View) 方法
public void makeToast(String text, View v) {
Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
int xOffset = 0;
int yOffset = 0;
Rect gvr = new Rect();
View parent = v;// // v is the editText,
// parent is the rectangle holding it.
if (parent.getGlobalVisibleRect(gvr)) {
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(getActivity(), text, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, xOffset, yOffset);
toast.show();
}