繁体   English   中英

类有 onTouchEvent 时如何使用 onCLick

[英]How to use onCLick when class has onTouchEvent

我有课 :

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
}

我使用它:

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

注释 onTouchEvent(块 A)时,onClick 中的代码是有效的。 使用 onTouchEvent(块 A)时,onClick 中的代码不起作用。

同时使用onTouchEvent时如何运行OnClick代码

我找到了解决方案 所以使用 dispatchTouchEvent 而不是 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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