For me, the following approach is great for new versions of Android - I tested it using Android 4.2 and Android 5.0.1.
The idea is that I will replace the appearance of the action icon with a custom view. Here I have to handle one click, and I can handle a long click.
If I want the look to be exactly like the usual action bar icons, the following is done.
First create a layout containing only ImageButton with your icon.
<?xml version="1.0" encoding="utf-8"?> <ImageButton xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/myButton" style="?android:attr/actionButtonStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:contentDescription="@layout/text_view_initializing" android:src="@drawable/ic_action_plus" />
Then put this ImageButton in the action bar and attach listeners to it.
MenuItem myItem = menu.findItem(R.id.my_action); myItem.setActionView(R.layout.my_image_button); myItem.getActionView().setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) {
Important note: this will only work if the item appears in the action bar. Thus, everything that you want to do with a long press will not be available this way if an option appears in the drop-down menu.
source share