如何在android中显示ToolTip?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11983936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to display ToolTip in android?
提问by Thiru
I want to display the ToolTip(QuickAction View) when I am moving my cursor on the view. Can any one please give me the simple example for it? tooltip will only contains the text value.
当我在视图上移动光标时,我想显示工具提示(QuickAction View)。任何人都可以给我一个简单的例子吗?工具提示将只包含文本值。
采纳答案by Tim Roes
Android supports "tool-tip" only for ActionBar buttons from Android 4.0 on. But as Jaguar already mentioned, tool-tips in Android doesnt make so much sense, since there is no concept of hovering.
从 Android 4.0 开始,Android 仅支持 ActionBar 按钮的“工具提示”。但是正如 Jaguar 已经提到的,Android 中的工具提示没有多大意义,因为没有悬停的概念。
From Android 4.0 the normal title text (that you set in the xml file or via code) will appear if you make a long click on the button. But if enough space is on the screen, it will be visible in the ActionBar all the time beside the icon.
从 Android 4.0 开始,如果您长按按钮,将出现正常的标题文本(您在 xml 文件中或通过代码设置)。但是,如果屏幕上有足够的空间,它将始终在 ActionBar 中的图标旁边可见。
If you want to have it for a custom view, you need to implement it yourself by adding a LongClickListener
to your view, and show a Toast
when pressed long:
如果您想将它用于自定义视图,则需要通过向LongClickListener
视图添加 a来自己实现它,并Toast
在长按时显示 a :
view.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
Toast.makeText(v.getContext(), "My tool-tip text", Toast.LENGTH_SHORT).show();
return true;
}
}
Of course you should use a resource for the string, and not the hard coded string.
当然,您应该为字符串使用资源,而不是硬编码的字符串。
回答by heisenberg
Possibly using myView.setTooltipText(CharSequence)
(from API-level 26) or TooltipCompat
(prior to API-level 26) is an additonal option:
可能使用myView.setTooltipText(CharSequence)
(来自 API 级别 26)或TooltipCompat
(在 API 级别 26 之前)是一个附加选项:
TooltipCompat.setTooltipText(myView, context.getString(R.string.myString));
Documentation says:
文档说:
Helper class used to emulate the behavior of {@link View#setTooltipText(CharSequence)} prior to API level 26.
用于模拟 API 级别 26 之前的 {@link View#setTooltipText(CharSequence)} 行为的辅助类。
回答by Darish
Using AndroidX is the recommended way.
使用 AndroidX 是推荐的方式。
Android 4.0 (API 14) and higher
Android 4.0 (API 14) 及更高版本
AndroidX support Library added support for tooltips(small popup windows with descriptive text) for views and menu items.
AndroidX 支持库为视图和菜单项添加了对工具提示(带有描述性文本的小弹出窗口)的支持。
Use setTooltipTextto set the tooltip text which will be displayed in a small popup next to the view.
使用setTooltipText设置工具提示文本,该文本将显示在视图旁边的小弹出窗口中。
See the following example:
请参阅以下示例:
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
TooltipCompat.setTooltipText(fab, "Send an email");
The tooltip will be displayed:
将显示工具提示:
- On long click, unless it is handled otherwise (by OnLongClickListener or a context menu).
- On hover, after a brief delay since the pointer has stopped moving
- 长按时,除非以其他方式处理(通过 OnLongClickListener 或上下文菜单)。
- 悬停时,在指针停止移动后的短暂延迟后
To add the Appcompat library into your project,
要将 Appcompat 库添加到您的项目中,
Open the build.gradle file for your application.
Add the support library to the dependencies section.
dependencies { compile "androidx.appcompat:appcompat:1.1.0" }
打开应用程序的 build.gradle 文件。
将支持库添加到依赖项部分。
dependencies { compile "androidx.appcompat:appcompat:1.1.0" }
Android 8.0 (API level 26) and higher
Android 8.0(API 级别 26)及更高版本
If your minimum supported version is Android 8.0 (API level 26) and higher, you can specify the tooltip text in a View by calling the setTooltipText() method. You can also set the tooltipText property using the corresponding XML.
如果您支持的最低版本是 Android 8.0(API 级别 26)及更高版本,您可以通过调用 setTooltipText() 方法在视图中指定工具提示文本。您还可以使用相应的 XML 设置 tooltipText 属性。
To specify the tooltip text in your XML files, set the android:tooltipText attribute, as shown in the following example:
要在 XML 文件中指定工具提示文本,请设置 android:tooltipText 属性,如下例所示:
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:tooltipText="Send an email" />
To specify the tooltip text in your code, use the setTooltipText(CharSequence) method, as shown in the following example:
要在代码中指定工具提示文本,请使用 setTooltipText(CharSequence) 方法,如以下示例所示:
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setTooltipText("Send an email");
回答by Mani.K
Starting with Android API 14+, there is an event for hovering. You can do,
从 Android API 14+ 开始,有一个用于 hovering的事件。你可以做,
view.setOnHoverListener(...)
and listen for MotionEvent
s such as ACTION_HOVER_ENTER
and ACTION_HOVER_EXIT
, instead of onLongClick
.
并聆听MotionEvent
诸如ACTION_HOVER_ENTER
and 之类的s ACTION_HOVER_EXIT
,而不是onLongClick
。
回答by ban-geoengineering
Based on GregoryK's answer, I've created a new ImageButton class - see code below. To use it, all you need to do is replace the ImageButton
in your layouts with com.yourpackage.ImageButtonWithToolTip
and give it an android:contentDescription
attribute (as that is the text that will be shown in the tool tip).
根据GregoryK 的回答,我创建了一个新的 ImageButton 类 - 请参阅下面的代码。要使用它,你需要做的是取代ImageButton
在您的布局com.yourpackage.ImageButtonWithToolTip
,并给它一个android:contentDescription
属性(因为这是将在工具提示中给出的文本)。
package com.yourpackage;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
public class ImageButtonWithToolTip extends ImageButton {
private static final int ESTIMATED_TOAST_HEIGHT_DIPS = 48;
public ImageButtonWithToolTip(Context context) {
super(context);
init();
}
public ImageButtonWithToolTip(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ImageButtonWithToolTip(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@TargetApi(21)
public ImageButtonWithToolTip(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
/**
* You should set the android:contentDescription attribute in this view's XML layout file.
*/
String contentDescription = getContentDescription().toString();
if (TextUtils.isEmpty(contentDescription)) {
/**
* There's no content description, so do nothing.
*/
return false; // Not consumed
}
else {
final int[] screenPos = new int[2]; // origin is device display
final Rect displayFrame = new Rect(); // includes decorations (e.g. status bar)
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 toolTipToast = Toast.makeText(context, contentDescription, Toast.LENGTH_SHORT);
boolean showBelow = screenPos[1] < estimatedToastHeight;
if (showBelow) {
// Show below
// Offsets are after decorations (e.g. status bar) are factored in
toolTipToast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL,
viewCenterX - screenWidth / 2,
screenPos[1] - displayFrame.top + viewHeight);
}
else {
// Show above
// Offsets are after decorations (e.g. status bar) are factored in
// NOTE: We can't use Gravity.BOTTOM because when the keyboard is up
// its height isn't factored in.
toolTipToast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL,
viewCenterX - screenWidth / 2,
screenPos[1] - displayFrame.top - estimatedToastHeight);
}
toolTipToast.show();
return true; // Consumed
}
}
});
}
}
You can use the same approach for extending other views - for example, Button
.
您可以使用相同的方法扩展其他视图 - 例如,Button
.
回答by GregoryK
If you need to show tool tip for any view, you can use CheatSheet
util class from Roman Nurik. (Uses Toast
and optionally content description
to show tooltip.)
如果您需要为任何视图显示工具提示,您可以使用CheatSheet
Roman Nurik 的 util 类。(使用Toast
和 可选content description
地显示工具提示。)
It is
这是
Android helper class for showing cheat sheets (tooltips) for icon-only UI elements on long-press. This is already default platform behavior for icon-only action bar items and tabs. This class provides this behavior for any other such UI element
用于在长按时显示仅图标 UI 元素的备忘单(工具提示)的 Android 助手类。这已经是仅限图标的操作栏项目和选项卡的默认平台行为。此类为任何其他此类 UI 元素提供此行为
回答by Jainendra
Android doesn't have tool tips. It is a touch-based UI. Current touch sensors can't generally detect hovering in a way that tool tips would be useful.
Android 没有工具提示。它是一个基于触摸的用户界面。当前的触摸传感器通常无法以工具提示有用的方式检测悬停。
There's no concept of "hovering" in a touch screen, but you could set a LongClickListenerfor your View, and have a Toast appear after a long press.
在触摸屏中没有“悬停”的概念,但您可以为您的视图设置一个LongClickListener,并在长按后显示一个 Toast。
回答by kartheek134
package com.nbfc.tekis.tooltipexample;
import android.support.v7.app.AppCompatActivity; import
android.os.Bundle; import android.view.View; import
android.widget.Button; import android.widget.GridView;
import it.sephiroth.android.library.tooltip.Tooltip;
public class MainActivity extends AppCompatActivity {
/*Button button1,button2,button3,button4;*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void bottomTooltip(View view) {
Button button1=(Button)findViewById(R.id.button1);
Tooltip.make(this,new Tooltip.Builder()
.anchor(button1, Tooltip.Gravity.BOTTOM)
.closePolicy(new Tooltip.ClosePolicy()
.insidePolicy(true,false)
.outsidePolicy(true,false),4000)
.activateDelay(900)
.showDelay(400)
.text("Android tooltip bottom")
.maxWidth(600)
.withArrow(true)
.withOverlay(true)
.build())
.show();
}
public void topTooltip(View view) {
Button button3=(Button)findViewById(R.id.button3);
Tooltip.make(this,new Tooltip.Builder()
.anchor(button3, Tooltip.Gravity.TOP)
.closePolicy(new Tooltip.ClosePolicy()
.insidePolicy(true,false)
.outsidePolicy(true,false),4000)
.activateDelay(900)
.showDelay(400)
.text("Android tooltip top")
.maxWidth(600)
.withOverlay(true)
.withArrow(true)
.build())
.show();
}
public void rightTooltip(View view) {
Button button2=(Button)findViewById(R.id.button2);
Tooltip.make(this,new Tooltip.Builder()
.anchor(button2, Tooltip.Gravity.RIGHT)
.closePolicy(new Tooltip.ClosePolicy()
.insidePolicy(true,false)
.outsidePolicy(true,false),4000)
.activateDelay(900)
.showDelay(400)
.text("Android tooltip right")
.maxWidth(600)
.withArrow(true)
.withOverlay(true)
.build())
.show();
}
public void leftTooltip(View view) {
Button button4=(Button)findViewById(R.id.button4);
Tooltip.make(this,new Tooltip.Builder()
.anchor(button4, Tooltip.Gravity.LEFT)
.closePolicy(new Tooltip.ClosePolicy()
.insidePolicy(true,false)
.outsidePolicy(true,false),4000)
.text("Android tooltip left")
.maxWidth(600)
.withArrow(true)
.withOverlay(true)
.build())
.show();
}
}
回答by Dushyanth Kandiah
add this to your button
将此添加到您的按钮
android:tooltipText="Tooltip text goes here"
回答by ren
Based on ban's Answer, I've created this method.
基于禁令的答案,我创建了这个方法。
It does not assume anything about the toast size. Simply places the tool tip gravity based on where the view is relative to the window (i.e. left/right/above/below the center of the window). The toast always starts from center of the view and will stretch towards the right/left/bottom/top respectively.
它不对吐司大小做任何假设。只需根据视图相对于窗口的位置(即窗口中心的左/右/上方/下方)放置工具提示重力。Toast 总是从视图的中心开始,并将分别向右侧/左侧/底部/顶部伸展。
private static void setToastGravity(View view, Toast toast) {
final Rect viewRect = new Rect(); // view rect
final Rect windowRect = new Rect(); // window rect
view.getGlobalVisibleRect(viewRect);
view.getWindowVisibleDisplayFrame(windowRect);
int offsetX;
int offsetY;
int gravityX;
int gravityY;
if (viewRect.centerY() > windowRect.centerY()) {
// above
offsetY = windowRect.bottom - viewRect.centerY();
gravityY = Gravity.BOTTOM;
} else {
// tooltip below the view
offsetY = viewRect.centerY() - windowRect.top;
gravityY = Gravity.TOP;
}
if (viewRect.centerX() > windowRect.centerX()) {
// tooltip right of the view
offsetX = windowRect.right - viewRect.centerX();
gravityX = Gravity.END;
} else {
// tooltip left of the view
offsetX = viewRect.centerX() - windowRect.left;
gravityX = Gravity.START;
}
toast.setGravity(gravityX | gravityY, offsetX, offsetY);
}