触摸监听器无法在android上正常工作

问题描述

| 我的Android应用程序中的触摸侦听器有问题。 OnTouchLIstenr不适用于该视图,即ACTION_DOWN在侦听器中运行良好,但ACTION_UP不会调用。我不知道发生了什么问题。但是,如果我设置了虚拟点击侦听器,两者都可以正常工作。为什么会这样呢?
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ImageView image = (ImageView) findViewById(R.id.image);
    image.setonTouchListener(new OnTouchListener() {            
        @Override
        public boolean onTouch(View v,MotionEvent event) {
            ImageView img = (ImageView) v;
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN){
                img.setimageResource(R.drawable.port);
            }else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL){
                img.setimageResource(R.drawable.bar);
            }               
            return false;
        }
    });

}
    

解决方法

您可能会考虑返回\'true \',因为您正在处理touch事件。 链接到类似的问题。 adamp的回答,很有道理     ,
image.setOnTouchListener(new OnTouchListener() {            
        @Override
        public boolean onTouch(View v,MotionEvent event) {
            ImageView img = (ImageView) v;
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN){
                img.setImageResource(R.drawable.port);
            }else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL){
                img.setImageResource(R.drawable.bar);
            }               


       return true;
        }
    });
只需将
return true;
代替
return false;
并检查