-->

Change Android smooth scroll behaviour on click

2019-06-13 03:09发布

问题:

I have a ListView and with a Timer I control the scroll movement of this list by calling smoothScrollToPositionFromTop(position, offset, duration). The ListView has a listener for OnItemClickListener.

If an item is clicked while the smooth scroll is happening, the scroll stops but the onItemClick event is not triggered. In order to do so you need to click again on the item.

I want to know how to override this behaviour. I mean, if I click on an item while the smooth scroll is happening, apart from stopping the scroll, I want to trigger onItemClick on the item clicked.

I really don't know if there is an easy way to do this. I tried with a GestureDetector for the OnTouchListener of the list and I listen to the onSingleTapConfirmed in order to call performClick in there, but I don't know how to get the position of the item being press from the MotionEvent.

回答1:

I finally found a solution by using the GestureDetector:

final GestureDetector gestureDetector = new GestureDetector(MyActivity.this, 
  new GestureDetector.SimpleOnGestureListener(){
    public boolean onSingleTapConfirmed(MotionEvent e) {
        int position = listView.pointToPosition((int)e.getX(), (int)e.getY());
        if(position != ListView.INVALID_POSITION){
            listView.playSoundEffect(SoundEffectConstants.CLICK);
            //onItemClick code goes here
            //or call listView.performItemClick
            return true;
        }
        return false;
    };
});

listView.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }
});

listView.setSelector(android.R.color.transparent);

In my case, I added what I was doing in onItemClick inside onSingleTapConfirmed and removed the OnItemClickListener from the list. That's why I also added the playSoundEffect function to simulate the click.

In the last line I disable highlight on ListView click since lines got highlighted only when the smooth scroll was not happening. By disabling it I get the same behaviour for every click.