我正在尝试为网格视图制作水平滚动视图。我成功用水平滚动视图。但是现在我需要为同一个网格视图实现onItemClickListener。我使用GestureDetector.SimpleOnGestureListener和onTouchEvent进行水平滚动。如果我使用这个onItemClickListener不起作用。有人帮助我兼顾工作。提前谢谢。
答案 0 :(得分:1)
我最近不得不处理同样的问题,这就是我解决它的方法。
首先,我覆盖ListFragment / ListActivity中的默认onListItemClick
侦听器。然后在onTouchEvent
方法中,我设置了一个条件,当为true时,调用ListView的onListItemClick
。当操作等于MotionEvent.ACTION_UP
且条件满足时,将执行此调用。您必须首先确定哪些事件组成了您的视图的点击。我宣布我的是ACTION_DOWN
,紧接着是ACTION_UP
。当您准备好执行onListItemClick
时,您必须将实际项目的视图,位置和ID传递给方法。
请参阅下面的示例。
Class....{
private boolean clickDetected = true;
public boolean onTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
final int x = (int) ev.getX();
final int y = (int) ev.getY();
//if an action other than ACTION_UP and ACTION_DOWN was performed
//then we are no longer in a simple item click event group
//(i.e DOWN followed immediately by UP)
if (action != MotionEvent.ACTION_UP
&& action != MotionEvent.ACTION_DOWN)
clickDetected = false;
if (action == MotionEvent.ACTION_UP){
//check if the onItemClick requirement was met
if (clickDetected){
//get the item and necessary data to perform onItemClick
//subtract the first visible item's position from the current item's position
//to compensate for the list been scrolled since pointToPosition does not consider it
int position = pointToPosition(x,y) - getFirstVisiblePosition();
View view = getChildAt(position);
if (view != null){//only continue if a valid view exists
long id = view.getId();
performItemClick(view, position, id);//pass control back to fragment/activity
}//end if
}//end if
clickDetected= true;//set this to true to refresh for next event
}//end if
return super.onTouchEvent(ev);
....
}//end onTouchEvent
}//end class
此设置允许更大的灵活性,例如,如果您想设置长按,您可以执行与上面相同的操作,并简单检查ACTION_DOWN和ACTION_UP之间的时间差异。
另一种方法是获取启动操作的项目的位置,并将其与针对操作的项目进行检查,甚至为向下和向上操作(例如小于1秒)投入时间差异标准。