简体   繁体   中英

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;
    }};

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;
    }

There are no multiple touch events generated from different views its all touch events from same ImageView I did test like below

Have a trace the viewID from which it

 ImageView imageView = (ImageView) findViewById(R.id.imageView);
 Log.i("Tag","ImageView ID :"+imageView.getId());
 imageView.setOnTouchListener(new View.OnTouchListener()
 {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            Log.i("Tag","OnTouch View ID :"+v.getId());
            return true;
        }
 });

and when you return true from onTouch event will be consumed.

and here is output

ImageView ID :2131230721

OnTouch View ID :2131230721
OnTouch View ID :2131230721
OnTouch View ID :2131230721

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM