Skip to content

Instantly share code, notes, and snippets.

@hector6872
Created August 24, 2016 23:44
Show Gist options
  • Save hector6872/4d981bf9d8db753272ad9cdb1c5e425e to your computer and use it in GitHub Desktop.
Save hector6872/4d981bf9d8db753272ad9cdb1c5e425e to your computer and use it in GitHub Desktop.
ToolTipView
/*
* +info: https://gist.github.com/romannurik/3982005
*/
public class ToolTipView {
public static final int LENGTH_SHORT = Toast.LENGTH_SHORT;
public static final int LENGTH_LONG = Toast.LENGTH_LONG;
@Retention(RetentionPolicy.CLASS) @IntDef({ LENGTH_SHORT, LENGTH_LONG }) public @interface Duration {
}
private static final int ESTIMATED_TOAST_HEIGHT_DIPS = 48;
public static void show(@NonNull View view, @NonNull CharSequence text, @Duration int duration) {
if (view == null || TextUtils.isEmpty(text)) {
return;
}
final int[] screenPos = new int[2];
final Rect displayFrame = new Rect();
view.getLocationOnScreen(screenPos);
view.getWindowVisibleDisplayFrame(displayFrame);
final Context context = view.getContext();
final int viewWidth = view.getWidth();
final int viewHeight = view.getHeight();
final int viewCenterX = screenPos[0] + viewWidth / 2;
final int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
final int estimatedToastHeight = (int) (ESTIMATED_TOAST_HEIGHT_DIPS * context.getResources().getDisplayMetrics().density);
Toast toast = Toast.makeText(context, text, duration);
boolean showBelow = screenPos[1] < estimatedToastHeight;
if (showBelow) {
toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, viewCenterX - screenWidth / 2,
screenPos[1] - displayFrame.top + viewHeight);
} else {
toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, viewCenterX - screenWidth / 2,
screenPos[1] - displayFrame.top - estimatedToastHeight);
}
toast.show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment