Skip to content

Instantly share code, notes, and snippets.

@adil-hussain-84
Last active November 25, 2017 12:20
Show Gist options
  • Save adil-hussain-84/45a6422765b3bb8f14544c8ac225904e to your computer and use it in GitHub Desktop.
Save adil-hussain-84/45a6422765b3bb8f14544c8ac225904e to your computer and use it in GitHub Desktop.
Show a Toast which is positioned to the left of a given View. The message in the Toast is the content description of the View.
/**
* Shows a {@link Toast} which is positioned to the left of a given {@link View}.
* The message in the {@link Toast} is the content description of the {@link View}.
* <p>
* Much of the code in this method is inspired by <a href="https://stackoverflow.com/a/21026866/1071320">this</a> StackOverflow answer.
*/
private void showContentDescriptionOfViewAsToast(View view) {
// toasts are positioned relative to the decor view and views relative to their parents;
// we have to gather additional data to have a common coordinate system
Rect rect = new Rect();
getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
int[] viewLocation = new int[2];
view.getLocationInWindow(viewLocation);
// covert view's absolute position to a position which is relative to the decor view
int viewLeft = viewLocation[0] - rect.left;
int viewTop = viewLocation[1] - rect.top;
Toast toast = Toast.makeText(getContext(), view.getContentDescription(), Toast.LENGTH_SHORT);
int toastHeight = getToastHeight(toast);
int viewHeight = view.getHeight();
int screenWidthPixels = getResources().getDisplayMetrics().widthPixels;
int horizontalMargin = getResources().getDimensionPixelOffset(R.dimen.view_horizontal_margin);
int toastXOffset = (screenWidthPixels - viewLeft) + horizontalMargin;
int toastYOffset;
if (viewHeight > toastHeight) {
toastYOffset = viewTop + ((viewHeight - toastHeight) / 2);
} else {
toastYOffset = viewTop - ((toastHeight - viewHeight) / 2);
}
toast.setGravity(Gravity.RIGHT | Gravity.TOP, toastXOffset, toastYOffset);
toast.show();
return true;
}
/**
* @return the measured height of the given {@link Toast}.
*/
private int getToastHeight(Toast toast) {
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels, View.MeasureSpec.UNSPECIFIED);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels, View.MeasureSpec.UNSPECIFIED);
toast.getView().measure(widthMeasureSpec, heightMeasureSpec);
return toast.getView().getMeasuredHeight();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment