0

I have class :

class MyLinearLayout extends LinearLayout {

    public ProLinearLayout(Context context, String options) {
        super(context);

        something();
    }
    private void something() {
        // .....
    }

    -- begin block A
    @Override
    public boolean onTouchEvent(MotionEvent event) { 
        int action = event.getAction();
        if ( action == MotionEvent.ACTION_DOWN ) {
            getBackground().setColorFilter( Color.GRAY, PorterDuff.Mode.ADD );
            invalidate();
        }
        if ( action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP ) {
            getBackground().clearColorFilter();
            invalidate();
        }
        return true;
    }
    -- end block A
}

An I use it :

MyLinearLayout obj = new MyLinearLayout( this_activity);
...
obj.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        // if comment block A, this this code works

        // if using bock A, this code does not work -- WHY. HOW TO RUN THIS CODE WHEN USING BLOCK A
    }
});

When comment onTouchEvent ( block A), the code in onClick is work. When using onTouchEvent ( block A), the code in onClick does not work.

How to run OnClick code when using onTouchEvent same time

quanlevan
  • 33
  • 6
  • you don't need to. You can simply implement OnTouch as OnClick. Refer to these links https://stackoverflow.com/a/19539206/6845131 and https://stackoverflow.com/a/9123001/6845131 – Vishist Varugeese Mar 20 '20 at 13:58

1 Answers1

1

I have found a solution So use dispatchTouchEvent instead of onTouchEvent

    -- begin block A
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        // 
        int action = event.getAction();
        if ( action == MotionEvent.ACTION_DOWN ) {
            getBackground().setColorFilter( Color.GRAY, PorterDuff.Mode.ADD );
            invalidate();
        }
        if ( action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP ) {
            getBackground().clearColorFilter();
            invalidate();
        }
        // 
        return super.dispatchTouchEvent(event);
    }
    -- end block A
quanlevan
  • 33
  • 6