按住按钮时重复一个字符

时间:2013-03-02 15:53:46

标签: android

只要按住按钮,我就要反复打印一封信。 例如,如果我按 R 2秒钟,我应该看到: "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”?

1 个答案:

答案 0 :(得分: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;
    }
});