2

我正在尝试收听触摸释放,但没有触发该事件。

这是我的代码:

public class MyView extends View {
    public MyView(final Context context) {
        super(context);
        setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent e) {
                if (e.getAction() == MotionEvent.ACTION_DOWN) {
                    makeToast("press", context);
                } else if (e.getAction() == MotionEvent.ACTION_UP || e.getAction() == MotionEvent.ACTION_CANCEL) {
                    makeToast("release", context);
                }

                return false;
            }
        });
    }

    void makeToast(String s, Context c) {
        CharSequence text = s;
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(c, text, duration);
        toast.show();
    }

}

活动类:

public class MyActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyView v = new MyView(getApplicationContext());
        setContentView(v);
    }
}

发生的情况是,当我触摸屏幕时,会出现一个写有“按下”的吐司,但是当我松开触摸时,没有出现吐司,而我期待一个写有“释放”的吐司出现。

我错过了什么?

4

1 回答 1

3

您需要在 onTouchListener 中返回 true 而不是 false。

发生的情况是首先触发了 Action Down 但您返回 false 意味着 Action Down 没有被处理。

如果您返回 true,它将确保它捕获的每个动作都得到完全处理,只有当您知道需要其他视图来处理该动作时,您才会返回 false。

祝你好运!

于 2013-11-06T21:06:32.953 回答