Change Android smooth scroll behaviour on click

爷,独闯天下 提交于 2019-12-08 12:33:04

问题


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.



来源:https://stackoverflow.com/questions/12802969/change-android-smooth-scroll-behaviour-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!