安卓开发小技巧

Toast调整显示位置

2018-10-12  本文已影响36人  蓝不蓝编程

背景:

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

image.png

解决方案:

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();
    }
image.png

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();
    }
image.png

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();
    }
image.png

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();
    }
image.png
上一篇 下一篇

猜你喜欢

热点阅读