Android examples for User Interface:View Click
Shows a Toast next to a view/button describing what it does This is basically copied over from ActionMenuItemView.onLongClick()
//package com.java2s; import android.content.Context; import android.graphics.Rect; import android.support.annotation.NonNull; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewCompat; import android.view.Gravity; import android.view.View; import android.widget.Toast; public class Main { /**/* w w w. ja va 2s . c o m*/ * Shows a Toast next to a view/button describing what it does * * This is basically copied over from ActionMenuItemView.onLongClick() * * @param anchorView The view where the toast will appear next to * @param text the text inside the Toast */ public static void showToolTip(@NonNull View anchorView, @NonNull CharSequence text) { final int[] screenPos = new int[2]; final Rect displayFrame = new Rect(); anchorView.getLocationOnScreen(screenPos); anchorView.getWindowVisibleDisplayFrame(displayFrame); final Context context = anchorView.getContext(); final int width = anchorView.getWidth(); final int height = anchorView.getHeight(); final int midy = screenPos[1] + height / 2; int referenceX = screenPos[0] + width / 2; if (ViewCompat.getLayoutDirection(anchorView) == ViewCompat.LAYOUT_DIRECTION_LTR) { final int screenWidth = context.getResources() .getDisplayMetrics().widthPixels; referenceX = screenWidth - referenceX; // mirror } Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT); if (midy < displayFrame.height()) { // Show along the top; follow action buttons toast.setGravity(Gravity.TOP | GravityCompat.END, referenceX, screenPos[1] + height - displayFrame.top); } else { // Show along the bottom center toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, height); } toast.show(); } /** * Similar to {@link #showToolTip(View, CharSequence)}, but takes in a string resource instead */ public static void showToolTip(@NonNull View anchorView, int textResource) { showToolTip(anchorView, anchorView.getResources().getString(textResource)); } /** * Similar to {@link #showToolTip(View, CharSequence)}, but displays the view's contentDescription */ public static void showToolTip(@NonNull View view) { showToolTip(view, view.getContentDescription()); } }