How to prevent onTouch for parent Linear Layout from executing multiple times child?

匆匆过客 提交于 2019-12-02 12:43:57

First, remove android:focusable="true" and android:focusableInTouchMode="true" from layout_button_sub and layout_button_find in your layout xml. This prevents the first touch/click event from being consumed by a focus change.

Then, change your OnTouchListener to an OnClickListener:

private class mOnClickListener implements OnClickListener
{
    Intent intent;

    public void onClick(View v)
    {
       switch (v.getId()) 
       {
           case R.id.layout_button_sub: 
                intent = new Intent(AppActivity.this, Subs.class);
                break;
           case R.id.layout_button_find: 
                intent = new Intent(AppActivity.this, Find.class);
                break; 
        }

        if (intent != null) 
        {
            startActivity(intent); 
        } 
    }       
}

And set it as such for your LinearLayouts:

mOnClickListener listener = new mOnClickListener();
linearLayoutSubs.setOnClickListener(listener);
linearLayoutFind.setOnClickListener(listener);

The onTouch() event fires on several MotionEvents: ACTION_DOWN, ACTION_MOVE, etc. Every time you "clicked" with an OnTouchListener, the method was firing, at minimum, once when you put your finger down and once when you lifted your finger. Since your original onTouch() method didn't account for the different actions, startActivity() was being called for every touch event.

I guess the problem is because you have not defined actions MOVE, UP and DOWN for the touch. Try writing your code in MotionEvent.ACTION_DOWN, If this works for you.

    case R.id.layout_button_subscriptions:{   
      switch (event.getAction()) {
                        case MotionEvent.ACTION_MOVE: 
                              {

                                 break;
                              }
                        case MotionEvent.ACTION_DOWN: {

                            startActivity(new Intent(AppActivity.this,Subs.class));
                        break;
                    }
    }

First mistake from the code I can see is that you are setting on touch listener twice, instead of the do following

mOnTouchListener listener =  new mOnTouchListener();
linearLayoutSubs.setOnTouchListener(listener);
linearLayoutFind.setOnTouchListener(listener);

if possible use the if else condition in the onTouch and whenever the onTouch has happend return true from that position only.

since many times it's not returning from that position and hence the event is fired twice.

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