android.widget.Toast定义了一堆有用的方法,允许自定义 Toast 通知的外观和感觉。你应该研究的方法是setGravity(int, int, int) http://developer.android.com/reference/android/widget/Toast.html#setGravity%28int,%20int,%20int%29。如果偏移量为 0,下面的代码会将 toast 顶部锚定到所提供视图的底部,并将 toast 中心锚定到视图的中心。
public static void positionToast(Toast toast, View view, Window window, int offsetX, int offsetY) {
// toasts are positioned relatively to decor view, views relatively to their parents, we have to gather additional data to have a common coordinate system
Rect rect = new Rect();
window.getDecorView().getWindowVisibleDisplayFrame(rect);
// covert anchor view absolute position to a position which is relative to decor view
int[] viewLocation = new int[2];
view.getLocationInWindow(viewLocation);
int viewLeft = viewLocation[0] - rect.left;
int viewTop = viewLocation[1] - rect.top;
// measure toast to center it relatively to the anchor view
DisplayMetrics metrics = new DisplayMetrics();
window.getWindowManager().getDefaultDisplay().getMetrics(metrics);
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(metrics.widthPixels, MeasureSpec.UNSPECIFIED);
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(metrics.heightPixels, MeasureSpec.UNSPECIFIED);
toast.getView().measure(widthMeasureSpec, heightMeasureSpec);
int toastWidth = toast.getView().getMeasuredWidth();
// compute toast offsets
int toastX = viewLeft + (view.getWidth() - toastWidth) / 2 + offsetX;
int toastY = viewTop + view.getHeight() + offsetY;
toast.setGravity(Gravity.LEFT | Gravity.TOP, toastX, toastY);
}
使用它需要修改您的 toast 相关行onClick method:
int offsetY = getResources().getDimensionPixelSize(R.dimen.toast_offset_y);
Toast toast = Toast.makeText(MainActivity.this, "That number is greater than 100. Not Valid!", Toast.LENGTH_SHORT);
positionToast(toast, v, getWindow(), 0, offsetY);
toast.show();