I created a custom component with both onTouchListener and a gesture detector. I put the custom component in the MainActivity XML file, which also has onTouchEvent and a gesture detector. I want to detect single taps on a user component and press MainActivity for a long time, but it seems that touch listeners are interacting somehow and single taps are never detected.
MainActivity.java:
public class MainActivity extends ActionBarActivity { private GestureDetector detector; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); detector = new GestureDetector(this, new LongPressDetector()); } @Override public boolean onTouchEvent(MotionEvent event) { detector.onTouchEvent(event); int action = event.getActionMasked(); switch (action){ case MotionEvent.ACTION_DOWN:{ Log.d("TouchEvent", "Action_Down at MainActivity.java"); break; } } return super.onTouchEvent(event); } private class LongPressDetector extends GestureDetector.SimpleOnGestureListener{ @Override public boolean onDown(MotionEvent e) { Log.d("TouchEvent", "onDown at MainActivity.java"); return super.onDown(e); } @Override public void onLongPress(MotionEvent e) { Log.d("TouchEvent", "onLongPress at MainActivity.java"); super.onLongPress(e); } } }
CustomView.java:
public class CustomView extends RelativeLayout { private GestureDetector detector; public CustomView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context c){ LayoutInflater layoutInflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); layoutInflater.inflate(R.layout.customview, this); detector = new GestureDetector(c, new TapDetector()); this.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { detector.onTouchEvent(event); int action = event.getActionMasked(); switch (action){ case MotionEvent.ACTION_DOWN:{ Log.d("TouchEvent", "Action_Down at CustomView.java"); break; } } return false; } }); } private class TapDetector extends GestureDetector.SimpleOnGestureListener{ @Override public boolean onDown(MotionEvent e) { Log.d("TouchEvent", "onDown at CustomView.java"); return super.onDown(e); } @Override public boolean onSingleTapUp(MotionEvent e) { Log.d("TouchEvent", "onSingleTapUp at CustomView.java"); return super.onSingleTapUp(e); } } }
source share