androidhorizontalscrollview

How to trigger onClickListener for HorizontalScrollView?


The question explains everything I want.

HorizontalScrollView seems to be the only widget for which setOnClickListener() does'nt trigger.

NOTE: I can't use onTouch event because on every touch it is triggered 4-5 times.

I also can't use onTouch on its parent view because parent view has many buttons with different functionality.


The following description is not important:

But still, these are the existing links I've searched(none helped):

horizontalscrollview onclicklistener doesn't get called

How to implement on click listener for horizontalscrollview

Click event of HorizontalScrollView

Android click event of items in HorizontalScrollView not respond after scroll

These are the links which I posted(none got answered completely):

Insert views in HorizontalScrollView programatically

One of the ImageButton not clicking & make HorizontalScrollView clickable

I asked multiple questions in these links, 1 of which was "onClickListener for HorizontalScrollView". That part of my question was never answered.

Hence an all exclusive question.


Solution

  • I came up with two ways of doing it.

    The simpler (but less ideal) one:

        HorizontalScrollView scrollView = (HorizontalScrollView) findViewById(R.id.scrollView);
    
        scrollView.setOnTouchListener(new OnTouchListener() {
    
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    // Do stuff
                }
                return false;
            }
        });
    

    This will get called only once when you click, drag or whatever you do with your finger. However, it will also react to all kinds of gestures, so if you want to detect only tap/click events, you need to further investigate the "event" object and filter out events you don't need. This may be more work than you would like, so you should better use a GestureDetector to do it for you.

    This leads to method 2:

        HorizontalScrollView scrollView = (HorizontalScrollView) findViewById(R.id.scrollView);
    
        final GestureDetector detector = new GestureDetector(this, new OnGestureListener() {
    
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                // Do stuff.
                return false;
            }
    
            // Note that there are more methods which will appear here 
            // (which you probably don't need).
        });
    
    
        scrollView.setOnTouchListener(new OnTouchListener() {
    
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                detector.onTouchEvent(event);
                return false;
            }
        });