Show toast widget underneath a view

后端 未结 6 1780
别那么骄傲
别那么骄傲 2020-11-29 12:05

For those who helped me out earlier regarding this project, thank you very much! My code no longer has any problems, and I made extra tweaks. Now that the app is actually ro

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 12:55

    android.widget.Toast defines a bunch of useful methods that allow customizing look and feel of a toast notification. Method you should look into is setGravity(int, int, int). With 0 offsets code below will anchor toast top to the bottom of the provided view and toast center to the center of the view.

    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);
    }
    

    Using it will require modifying toast related lines in your 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();
    

提交回复
热议问题