android - 按住按钮时重复一个字符

标签 android

只要按住按钮,我就想一遍又一遍地打印一封信。 例如,如果我按 R 2 秒,我应该看到: “RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR”

我尝试过这个:

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”重复?

最佳答案

it's work when move the finger
i want use it without moveing

您需要使用回调。通过使用 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;
    }
});

关于android - 按住按钮时重复一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15176368/

相关文章:

android - 绘画 Canvas 机器人

java - Android Eclipse - 找不到 *.apk

java - 使用 Intent 启动新的 Activity。 NPE 位于 android.content.ContextWrapper.getPackageName

android - 在 ListView 中创建 ListView

javascript - 在移动网络浏览器上创建和使用带有 javascript api 的 youtube 嵌入对象

android - 构建通知时出错

android - android中的谷歌浏览器动画效果

android - 九色背景的理想尺寸

c# - 使用 C# Web 服务将图像从 Android 应用程序上传到服务器

android - 授予 Uri 对另一个 Activity 的权限