2017-06-05 69 views
0

是否可以對菜單項目執行長按操作以執行特定操作? 當我長按某個項目時,我試圖讓菜單下拉菜單。長按Android菜單項?

這裏的菜單XML

<item 
    android:id="@+id/add_item" 
    android:icon="@drawable/ic_add_black_24dp" 
    android:showAsAction="ifRoom" 
    android:title="Add Item"> 
</item> 

<item 
    android:id="@+id/open_menu" 
    android:icon="@drawable/ic_menu_black_24dp" 
    android:showAsAction="ifRoom|withText" 
    android:title="Open Menu"> 
</item> 

我想有一個下拉菜單出現時,第一項長按

回答

1

您可以HandlerRunnable做到這一點。在run()方法內部,獲取您想要的MenuItemView並將onLongClick設置爲View

這裏是工作代碼:

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

    new Handler().post(new Runnable() { 
     @Override 
     public void run() { 
      final View view = findViewById(R.id.add_item); 

      if (view != null) { 
       view.setOnLongClickListener(new View.OnLongClickListener() { 
        @Override 
        public boolean onLongClick(View v) { 

         // Do something... 

         Toast.makeText(getApplicationContext(), "Long pressed", Toast.LENGTH_SHORT).show(); 
         return true; 
        } 
       }); 
      } 
     } 
    }); 

    return super.onCreateOptionsMenu(menu); 
} 

OUTPUT:

enter image description here

0

這裏是另一個解決你的問題。 我已經在res /菜單/如下menu.xml文件中使用的菜單:

<menu xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item 
     android:id="@+id/action_send" 
     android:orderInCategory="100" 
     android:title="@string/send_menu" 
     app:showAsAction="always" /> 
</menu> 

這裏是我的活動類。我已經爲菜單項添加了一個圖像按鈕併爲其設置圖像資源。 Backgroud被設置爲null以具有透明的菜單項。

public class MyActivity extends AppCompatActivity { 
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.menu, menu); 
     MenuItem item = menu.findItem(R.id.action_send); 
     ImageButton imageButton = new ImageButton(this); 
     imageButton.setImageResource(R.drawable.ic_send_white_24dp); 
     imageButton.setBackground(null); 
     item.setActionView(imageButton); 
     item.getActionView().setOnLongClickListener(new View.OnLongClickListener() { 
      @Override 
      public boolean onLongClick(View v) { 
       Log.d("Send Button", "Long pressed"); 
       Toast.makeText(MainActivity.this, "Send button long pressed", Toast.LENGTH_LONG).show(); 
       onSendMenuItemLongClick(); 
       return true; 
      } 
     }); 

     item.getActionView().setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       onSendMenuItemClick(item); 
      } 
     }); 

     return super.onCreateOptionsMenu(menu); 
    } 

    private void onSendMenuItemLongClick() { 

    } 

    private void onSendMenuItemClick(MenuItem item) { 
     Toast.makeText(this, "Send button clicked", Toast.LENGTH_LONG).show(); 
    } 
}