安卓:强制onKeyListener等待 [英] Android: force onKeyListener to wait

查看:206
本文介绍了安卓:强制onKeyListener等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有难同当相关的一些操作的用户类型的东西在AutocompleteTextView。不过,我只希望当用户停止输入注册的动作。从本质上讲,我不想要的操作,而用户垃圾邮件打字发生。下面code可能会更好一点解释。

I currently have some action associated with when the user types something in a AutocompleteTextView. However, I only want the action to register if the user stops typing. Essentially, I don't want the action to happen while the user to spam typing. The following code might explain it a little better.

AutocompleteTextView search = ...;
search.setOnKeyListener(new onKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_UP) {
            if (mTimer != null)
                mTimer.cancel();
            mTimer = new Timer();
            mTimer.schedule(new TimerTask() {
                public void run() {
                    my_func();
                }
            }, 1000);
            return true;
        }
        return false;
    }
}

public void my_func() {
    Looper.prepare();

    // Do some function that changes the View

    Looper.loop();
}

任何想法我怎么能强迫的KeyListener等待若干秒?

Any ideas how I can force the keyListener to wait a certain number of seconds?

编辑:

我现在用的定时器调度功能。请参阅上述编辑code。

I am now using Timer to schedule the function. Refer to above edited code.

第一个定时器工作。然而,当我试图重新唤起人们对函数的第二个计时器,我得到的只说初始化过的视图可以修改浏览主线程异常。我不知道活套是如何工作的(我只是说活套,因为在此之前,我需要使用它抱怨)。有什么建议?

The FIRST timer works. However, when I try to re-evoke the function the second timer, I get an exception that says only main thread that initialized the View can modify the View. I am not sure how Looper works (I just added Looper because it complained before that I need to use it). Any suggestions?

推荐答案

创建一个定时器。当计时器火灾,做你的行动。如果您收到另一个关键preSS计时器到期之前,取消计时器,并重新设置。喜欢的东西,

Create a Timer. When the Timer fires, do your action. If you receive another keypress before the Timer expires, cancel the timer, and reset it. Something like,

public boolean onKey(View v, int keyCode, KeyEvent event) {
  if (mTimer != null) {
    mTimer.cancel();
  }
  mTimer = new Timer();
  mTimer.schedule(new TimerTask() {
    @Override 
    public void run() {
      // do what you need to do after the one second here
      mTimer = null;
    }
  }, 1000);
}    

如果您从定时任务的里面修改视图树的run()方法,你必须强迫它在UI线程上发生。你可以做到这一点像,

If you modify the view tree from inside the timer task's run() method, you must force it to happen on the UI thread. You can do this like,

YouActivity.this.runOnUiThread(new Runnable() {
  @Override
  public void run() {
    // modify your UI components here
  }
});

这篇关于安卓:强制onKeyListener等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆