2014-04-15 113 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");