How to handle click in the child Views, and touch in the parent ViewGroups?

这一生的挚爱 提交于 2019-11-27 18:29:10

问题


In my layout I have a structure like that:

--RelativeLayout
  |
  --FrameLayout
    |
    --Button, EditText...

I want to handle touch events in the RelativeLayout and in the FrameLayout, so I set the onTouchListener in these two view groups. But only the touch in the RelativeLayout is captured.

To try solve this, I wrote my own CustomRelativeLayout, and override the onInterceptTouchEvent, now the click in the child ViewGroup (FrameLayout) is captured, but the click in the buttons and other views doesn't make any effect.

In my own custom layout, I have this:

public boolean onInterceptTouchEvent(MotionEvent ev) {
    return true;
}

回答1:


You need to override the onInterceptTouchEvent() for each child, otherwise it will remain an onTouchEvent for the parent.

Intercept Touch Events in a ViewGroup

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    /*
    * This method JUST determines whether we want to intercept the motion.
    * If we return true, onTouchEvent will be called and we do the actual
    * scrolling there.
    */
...
    // In general, we don't want to intercept touch events. They should be 
    // handled by the child view.
    return false;
}

You need to return false to have the child handle it, otherwise you are returning it to the parent.




回答2:


Your custom solution will capture touch events from anywhere in your relative layout since the overridden method is set to always throw true.

For your requirement I guess its better to use the onClick method rather than using onTouch.

OnTouch method invokes different threads on every TouchEvent and I guess that is the cause of your problem

Rather than handling these events its better to try onClick method.




回答3:


I was able to solve this problem with the following code:

Step 1: declare the EditText above the onCreate () method

public EditText etMyEdit;

Step 2: in the onResume () method the configuration ends:

etMyEdit = (EditText) findViewById (R.id.editText);

etMyEdit.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            v.getParent().requestDisallowInterceptTouchEvent(true);
            switch (event.getAction() & MotionEvent.ACTION_MASK){
                case MotionEvent.ACTION_UP:
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                    return false;
            }
            return false;
        }
    });

Hope it helps someone!



来源:https://stackoverflow.com/questions/28179769/how-to-handle-click-in-the-child-views-and-touch-in-the-parent-viewgroups

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