由于可以为父LinearLayout分配其自己的OnClickListener,因此问题仅在于如何检测GridView中其子视图之外发生的单击.您可以继承GridView并覆盖dispatchTouchEvent()方法来完成此操作.使用pointToPosition()方法,我们可以确定触摸事件是否发生在子视图之外,并使用接口通知侦听器是否存在.在以下示例中,OnNoItemClickListener接口提供该功能.
public class TouchyGridView extends GridView
{
// Depending on how you're creating this View,
// you might need to specify additional constructors.
public TouchyGridView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
private OnNoItemClickListener listener;
public interface OnNoItemClickListener
{
public void onNoItemClick();
}
public void setOnNoItemClickListener(OnNoItemClickListener listener)
{
this.listener = listener;
}
@Override
public boolean dispatchTouchEvent(MotionEvent event)
{
// The pointToPosition() method returns -1 if the touch event
// occurs outside of a child View.
// Change the MotionEvent action as needed. Here we use ACTION_DOWN
// as a simple, naive indication of a click.
if (pointToPosition((int) event.getX(), (int) event.getY()) == -1
&& event.getAction() == MotionEvent.ACTION_DOWN)
{
if (listener != null)
{
listener.onNoItemClick();
}
}
return super.dispatchTouchEvent(event);
}
}