背景:

     Toast默认显示在界面底部,因这位置在部分界面会遮挡界面元素,故需要调整位置。

Toast调整显示位置_公众号

解决方案:

 1.显示在顶部

private void showToast(Context context,String text) {
Toast toast = Toast.makeText(context,text,Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP,0,0);
toast.show();
}

Toast调整显示位置_公众号_02

 2.显示在中间

private void showToast(Context context,String text) {
Toast toast = Toast.makeText(context,text,Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
}

Toast调整显示位置_计算机专业_03

3.显示在垂直方向1/3处

private void showToast(Context context, String text) {
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
WindowManager windowManager = (WindowManager) context.getSystemService(WINDOW_SERVICE);
Point size = new Point();
windowManager.getDefaultDisplay().getSize(size);
toast.setGravity(Gravity.TOP, 0, size.y / 3);
toast.show();
}

Toast调整显示位置_计算机专业_04

4.显示在垂直方向2/3

private void showToast(Context context, String text) {
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
WindowManager windowManager = (WindowManager) context.getSystemService(WINDOW_SERVICE);
Point size = new Point();
windowManager.getDefaultDisplay().getSize(size);
toast.setGravity(Gravity.BOTTOM, 0, size.y / 3);
toast.show();
}

Toast调整显示位置_计算机专业_05

关于我

厦门大学计算机专业 | 前华为工程师

分享编程技术,没啥深度,但看得懂,适合初学者。

Java | 安卓 | 前端 | 小程序 | 鸿蒙

公众号:花生皮编程

Toast调整显示位置_公众号_06