Home > DeveloperSection > Forums > How to detect click event at empty space of gridview inside linearlayout in android?
Norman Reedus
Norman Reedus

Total Post:45

Points:315
Posted on    November-19-2014 2:08 AM

 Android Java  Android Layout 
Ratings:


 1 Reply(s)
 1880  View(s)
Rate this:

I have a following problem. I have a GridView inside LinearLayout as image below. I want to detect click event when user click at empty space of GridView, in the image, the location that I want is the red area and also inside the green area.

But I have following problems.

  1. If I add onClickListener for GridView: error because Adapter cannot add click event.
  2. If I add onItemClickListener for GridView: I just can detect where exist items (in the image is the white box)
  3. If I add onClickListener for LinearLayout I just can detect click event on green area, not red area.

So how can I fix above problem.

@Edit: my layout looks like:

<LinearLayout>

  <GridView

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"/>

</LinearLayout>



Elena Glibart
Elena Glibart

Total Post:33

Points:233
Posted on    November-19-2014 7:01 AM

Since the parent LinearLayout can be assigned its own OnClickListener, the issue is only how to detect a click within the GridView that occurs outside of its child Views. You can subclass GridView and override the dispatchTouchEvent() method to accomplish this. Using the pointToPosition()method, we can determine if a touch event occurs outside of the child Views, and use an interface to notify a listener if it is. In the following example, the OnNoItemClickListener interface provides that functionality.

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);

    }

}


Don't want to miss updates? Please click the below button!

Follow MindStick