ShP ShP - 1 month ago 6
Android Question

Action Bar - Drag Menu Item

How can I setOnTouchListener to action bar menu item in order to add functionality to drag some item from action bar?

For example, if I do this:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item android:id="@+id/my_menu_item_button"
android:icon="@android:drawable/ic_menu_mylocation"
android:title="TEST"
app:showAsAction="always" />

</menu>


And try to do this:

final MenuItem myMenuItem = (MenuItem) findViewById(R.id.action_search);

myMenuItem.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent me) {
return true;
}
});


I can't because setOnTouchListener needs view.

Any solution for this?

Here's the skeleton:
https://gist.github.com/anonymous/b654b67d4dbd45ce8539

dex dex
Answer
View you can find easily by using menuItem.getActionView(), but I guess you get the action view as null if you have not set any custom view using MenuItem.setActionView().

Solution : 
Lets create a layout file called sample_action_view.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_gravity="center_vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/mobile_link_action_bar_button" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:src="sampleImage.png"
        android:contentDescription="Sample Image"/>    
</LinearLayout>


    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.menu_main, menu);

        LayoutInflater inflater = (LayoutInflater)this.getApplicationContext().getSystemService
                (Context.LAYOUT_INFLATER_SERVICE);
        View sampleActionView = inflater.inflate(R.layout.sample_action_view, null);
        MenuItem searchMenuItem = menu.findItem(R.id.menu_myDemoToolbarButton);
        serachMenuItem.setActionView(sampleActionView);

        sampleActionView.setOnTouchListener(new OnTouchListener() 
        {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                // TODO Auto-generated method stub
                return false;
            }
        });

        return super.onCreateOptionsMenu(menu);