這裏是另一個解決你的問題。 我已經在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();
}
}