我上课:
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