Android 即使长时间单击,也会执行Onclick事件
我使用的是Android 即使长时间单击,也会执行Onclick事件,android,listview,Android,Listview,我使用的是ExpandableListView lv。这就是我所拥有的 ExpandableListView lv=(ExpandableListView )findViewById(....); lv.setOnChildClickListener(new ExpandableListView.OnChildClickListener(){ @Override public boolean onChildClick(ExpandableListView parent, View v,i
ExpandableListView lv
。这就是我所拥有的
ExpandableListView lv=(ExpandableListView )findViewById(....);
lv.setOnChildClickListener(new ExpandableListView.OnChildClickListener(){
@Override
public boolean onChildClick(ExpandableListView parent, View v,int gp, int cp, long id) {
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
//perform action
return true;
}
});
lv.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu contextMenu, View v,ContextMenuInfo menuInfo) {
ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuInfo;
customMenu.show(v);
//do other stuff
contextMenu=null;
}
});
当我长时间单击子项时,会调用customMenu.show(v)
,当我抬起手指时,会调用其OnClickListener
。
类似地,长按然后松开组项目上的手指时,将调用其ContextmenuListener
,然后组将展开以显示子项目。这是正常的行为吗?我如何防止这种情况
实际上,我想在列表项上长按做一些事情。在longClickListener
上返回true
可以正常工作(使用单击事件)。
但我还需要获取项的id、组和子位置,这些信息仅通过ContextMenuInfo
侦听器中的ContextMenuInfo
提供
boolean isLongClick = false;
public void onClick(View arg0) {
if(isLongClick == false){ // this checks to see if it was long clicked
// Perform your action here
}
isLongClick = false; // resetting longClick to false after bypassing action
}
public boolean onLongClick(View arg0) {
isLongClick = true;
//perform other action here
return false;
}
这将运行两个操作侦听器,一个用于单击,另一个用于长时间单击。
如果用户长时间单击该对象,它会将布尔值设置为true,从而阻止该操作
在onClickListener中执行,但是无论发生什么,onClickListener仍然会激发,所以
我们确保在该方法中重置布尔值,以便在长时间按下后,该项目将再次接受单次按下
当然,这意味着您需要获得按下的项目的id等,但这种方法就像一个符咒。我刚刚在一个弹出菜单的应用程序中实现了它。
我想要两个不同的菜单弹出取决于用户是单按还是长按锚。因此,如果他们快速按下,它会弹出一个(打开)菜单,如果长时间按下,它会弹出一个(共享、编辑、删除)菜单等。确保
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
return true; //<-- this should be TRUE, not FALSE
}
@覆盖
长单击(AdapterView父视图、视图、,
内部位置,长id){
return true;//您不应该调用lv.registerForContextMenu()吗?嗯,当我试图通过添加一些菜单项来实际显示contextmenu时,它工作正常。但我不想这样做。我想显示我自己的菜单,就像在给定的代码中一样。我希望您找到更好的解决方案。