我有一个典型的菜单,我想为其中一个项目设置onLongClickListener
。换句话说,我希望这个项目能够执行它的正常onOptionsItemSelected
功能,以及长按功能。
MenuItem item;
item = menu.findItem(android.R.id.home);
item.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
Context context = getApplicationContext();
CharSequence text = "Long Press";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
return true;
}
});
答案 0 :(得分:1)
我只需在menuItem上使用setActionView即可。如果有帮助,您可以按照此程序进行操作。
for(int i = 0; i < menu.size(); i++){
View v = new View(this);
v.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
//Your longclick listener callback logic goes here
return false;
}
});
menu.getItem(i).setActionView(v);
}
答案 1 :(得分:0)
使用findItem
上的Menu
方法获取您的观看次数,并在每个视图上设置长按一次监听器。
答案 2 :(得分:0)
这种方法不对,它扰乱了整个流程,但是你走了:
private interface OnMenuItemLongClickListener{
boolean onMenuItemLongClik(MenuItem m);
}
private void getMenuItemsView(Activity a, final Menu m, final OnMenuItemLongClickListener listener) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException{
View homeButton = a.findViewById(android.R.id.home);
ViewParent parentOfHome = homeButton.getParent().getParent(); //ActionBarView is parent of home ImageView, see layout file in sources
if (!parentOfHome.getClass().getName().contains("ActionBarView")) {
parentOfHome = parentOfHome.getParent();
Class absAbv = parentOfHome.getClass().getSuperclass(); //ActionBarView -> AbsActionBarView class
Field actionMenuPresenterField = absAbv.getDeclaredField("mActionMenuPresenter");
actionMenuPresenterField.setAccessible(true);
Object actionMenuPresenter = actionMenuPresenterField.get(parentOfHome);
Field actionMenuViewField = actionMenuPresenter.getClass().getSuperclass().getDeclaredField("mMenuView");
actionMenuViewField.setAccessible(true);
Object actionMenuView = actionMenuViewField.get(actionMenuPresenter);
Field childrenField= actionMenuView.getClass().getSuperclass().getSuperclass().getDeclaredField("mChildren");
childrenField.setAccessible(true);
Field menuField =actionMenuPresenter.getClass().getSuperclass().getDeclaredField("mMenu");
menuField.setAccessible(true);
Object menu = menuField.get(actionMenuPresenter);
Object[] menuItemsAsViews = (Object[])childrenField.get(actionMenuView);
View.OnLongClickListener longListener = new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return listener.onMenuItemLongClik(m.findItem(v.getId()));
}
};
for(Object menuView:menuItemsAsViews ){
View v = (View)menuView;
v.setOnLongClickListener(longListener);
}
}
}
用法:
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
getMenuItemsViews(MainActivity.this, menu);
}}, 100); //must be called after the menu views are generated, otherwise NPE.
return super.onPrepareOptionsMenu(menu);
}
将考虑溢出WILL NOT
中的MenuItem。