Search code examples
androidandroid-layoutontouchlistener

How to disable onTouch of parent retaining onTouch of child in android


What I am having:

  • I am having a imageview on a linear layout. I want to detect onTouch of imageview.
  • I do not want to use onClick because my implementation requires onTouch Imageview is the child of linearLayout

What is happening:

  • Two touch events are firing when i click on image one from image and another from the linear layout(parent)

Question:

  • How can I disable onTouch of linearLayout(parent)retaining the onTouch of Imageview

Code:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    imgUsrClrId.setOnTouchListener(imgSourceOnTouchListener);
}


 OnTouchListener imgSourceOnTouchListener= new OnTouchListener(){

    @Override
    public boolean onTouch(View view, MotionEvent event) {

        Log.d("", "");

        return true;
    }};

Solution

  • Touch event is fired for only one view at a time, and here in your code touch event is fired for imageview but as we know touchListener will be called for every MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP, and MotionEvent.ACTION_MOVE. So if you want only one event to be fired at a time, ie MotionEvent.ACTION_DOWN or MotionEvent.ACTION_UP then write it in this way:

     @Override
     public boolean onTouchEvent(MotionEvent ev) {
    
            final int action = ev.getAction();
    
            switch (action) {
    
                // MotionEvent class constant signifying a finger-down event
    
                case MotionEvent.ACTION_DOWN: {
                     //your code
    
                    break;
                }
    
                // MotionEvent class constant signifying a finger-drag event  
    
                case MotionEvent.ACTION_MOVE: {
    
                       //your code
    
                      break;
    
                }
    
                // MotionEvent class constant signifying a finger-up event
    
                case MotionEvent.ACTION_UP:
                  //your code
    
                    break;
    
            }
            return true;
        }