2014-04-15 109 views
8

我试图建立一个图像按钮的应用程序,像行动栏一样工作,但我无法让他们在长按新闻时显示工具提示。安卓图像按钮工具提示

<ImageButton 
     android:id="@+id/editUrgent" 
     style="?android:attr/borderlessButtonStyle" 
     android:layout_width="48dp" 
     android:layout_height="wrap_content" 
     android:layout_centerVertical="true" 
     android:layout_toLeftOf="@+id/editImportant" 
     android:hint="@string/hint_urgent" 
     android:contentDescription="@string/hint_urgent" 
     android:text="@string/hint_urgent" 
     android:src="@drawable/clock_light" /> 

android:contentDescription适用于悬停(s-pen),但长按仍然不起作用。

+1

退房上下文菜单选项 - http://www.thegeekstuff.com/2013/12/android-app-menus/ –

回答

3

不完全是你在找什么,但它做的事情非常相似。

1)保证视图是android:longClickable="true"(应该是默认情况下),并且具有定义的内容描述android:contentDescription="@string/myText"

<ImageButton android:id="@+id/button_edit" 
    android:contentDescription="@string/myText" 
    android:src="@drawable/ic_action_edit" 
    android:onClick="onEdit" 
    android:longClickable="true"/> 

2)注册回调视图时长按压到被调用。处理程序将显示内容描述作为Toa​​st消息。

findViewById(R.id.button_edit).setOnLongClickListener(new View.OnLongClickListener() { 

      @Override 
      public boolean onLongClick(View view) { 
       Toast.makeText(context,view.getContentDescription(), Toast.LENGTH_SHORT).show(); 
       return true; 
      } 
     }); 
+0

这不是因为它不会显示提供长按的工具提示,但会显示在标准的Toast消息位置(??)中。 –

10

这是Support Library v7用来显示 “小抄” S行动菜单项的代码:

public boolean onLongClick(View v) { 
    if (hasText()) { 
     // Don't show the cheat sheet for items that already show text. 
     return false; 
    } 

    final int[] screenPos = new int[2]; 
    final Rect displayFrame = new Rect(); 
    getLocationOnScreen(screenPos); 
    getWindowVisibleDisplayFrame(displayFrame); 

    final Context context = getContext(); 
    final int width = getWidth(); 
    final int height = getHeight(); 
    final int midy = screenPos[1] + height/2; 
    int referenceX = screenPos[0] + width/2; 
    if (ViewCompat.getLayoutDirection(v) == ViewCompat.LAYOUT_DIRECTION_LTR) { 
     final int screenWidth = context.getResources().getDisplayMetrics().widthPixels; 
     referenceX = screenWidth - referenceX; // mirror 
    } 
    Toast cheatSheet = Toast.makeText(context, mItemData.getTitle(), Toast.LENGTH_SHORT); 
    if (midy < displayFrame.height()) { 
     // Show along the top; follow action buttons 
     cheatSheet.setGravity(Gravity.TOP | GravityCompat.END, referenceX, height); 
    } else { 
     // Show along the bottom center 
     cheatSheet.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, height); 
    } 
    cheatSheet.show(); 
    return true; 
} 
5

符合API级别26,你可以使用内置的ToolTipText: XML:

android:toolTipText="yourText" 

ViewCompatDocs

对于旧的API升evels使用ToolTipCompat,例如:长按这个功能

TooltipCompat.setTooltipText(yourView, "your String");