2

只要按住按钮,我就想一遍又一遍地打印一封信。例如,如果我推动R2 秒,我应该会看到: "RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR"

我试过这个:

public void addListenerOnUP() {
    Button b = (Button) findViewById(R.id.up);
    b.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            String p = "R";

            //print ...
            return true;
        }
    });
}

但它只在用户移动手指时有效,而不是在他们触摸屏幕时。我怎样才能让“R”重复?

4

1 回答 1

2

移动手指时它的工作
我想在不移动的情况下使用它

您需要使用回调。通过使用 Handler 和 Runnable,您可以在用户手指向下时以设定的时间间隔打印出一个新字母。(也许每 100 毫秒一次?)

private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // Print out your letter here...

        // Call the runnable again
        handler.postDelayed(this, 100);
    }
}

仅在用户手指向下时打印字母:

b.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()){
        case MotionEvent.ACTION_DOWN:
            // Start printing the letter in the callback now 
            handler.post(runnable);
            break;
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
            // Stop printing the letter
            handler.removeCallbacks(runnable);
        }
        return true;
    }
});
于 2013-03-02T16:04:26.347 回答