Toast调整显示位置

作者: 蓝不蓝编程 | 来源:发表于2018-10-12 09:20 被阅读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

    相关文章

      网友评论

        本文标题:Toast调整显示位置

        本文链接:https://www.haomeiwen.com/subject/nxjwaftx.html