Search code examples
androidandroid-listviewtouch-eventontouchlisteneronitemclicklistener

Android on touch listener inside an item click listener


I have a list view with items and every time I click on a List Item , I need to know if I have touched the left side or the right side of the screen. In order to accomplish this , I have coded the following:

 testListView.setOnItemClickListener(((parent, view, position, id) -> {

        view.setOnTouchListener(new View.OnTouchListener() {
            private long startClickTime = 0;
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {

                    startClickTime = System.currentTimeMillis();

                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {

                    if (System.currentTimeMillis() - startClickTime < ViewConfiguration.getTapTimeout()) {

                        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
                        float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
                        float leftPersentage = (dpWidth) * 100 / 100;
                        int x = (int) motionEvent.getX();
                        if (x < leftPersentage) {
                            Toast.makeText(context,"I have touched the left side of screen",Toast.LENGTH_SHORT);
                        } else {
                            Toast.makeText(context,"I have touched the right side of screen",Toast.LENGTH_SHORT);
                        }
                    }
                }
                return true;
            }
        });
    }));

This works , however , in order to make the Toast appear , I need to press TWICE the List element and I think that this is happening because the first time I click on the list item element , It registers the OnTouchListener and then , if I click again it fires up.

How can I fix this strange behaviour in order to trigger the on touch listener with only one click ?


Solution

  • you need to set your setOnTouchListener on the ListView adapter on getView function instead of on setOnItemClickListener.